// Apogee Results Conversion Tagging Ver 1.3.2 for fathomtheatrechurch.com 
/**
* added event for fathomtheatrechurch.com
*/

var apo132Results = {};
apo132Results.jquery = jQuery.noConflict();
apo132Results.jquery(document).ready(function ($) {

    function linkTrackingDelay(mseconds) {
        var currentTime = new Date();
        var endTime = currentTime.getTime() + mseconds;
        while (currentTime.getTime() < endTime) {
            currentTime = new Date();
        }
    }

    function sfTrackEvent(convType, eventType, transId, convAmount, subEvent) {
        var jAccountID = "33989";
        var jconversion_type = convType;
        var jValue = convAmount;
        var jOrderID = transId;
        var jvar1 = eventType;
        var jvar2 = subEvent;
        var jvar3 = "";
        var juAgent = navigator.userAgent;
        var imgURL = "//sftrack.searchforce.net/SFConversionTracking/img.jpg?jt=3"
	+ "&jaid=" + jAccountID + "&joid=" + escape(jOrderID) + "&jcv=" + jValue + "&je=" + jconversion_type
	+ "&jvar1=" + escape(jvar1) + "&jvar2=" + escape(jvar2) + "&jvar3=" + escape(jvar3)
	 + "&juag=" + juAgent;
        var convImg = new Image();
        convImg.src = imgURL;

        linkTrackingDelay(300);
    }

    function sfTrackSaleEvent(transId, itemDesc, saleAmount) {
        sfTrackEvent("Sale", itemDesc, transId, saleAmount, '');
    }

    function sfTrackConvEvent(convType, eventType, subEvent) {
        if (typeof subEvent == 'undefined') {
            subEvent = '';
        }
        sfTrackEvent(convType, eventType, '', '', subEvent);
    }



    function clickEventSale(transId, itemDesc, saleAmount, tax, shipping,
total) {
        sfTrackSaleEvent(transId, itemDesc, saleAmount);
    }





    function registerVenueInquiry(transId, itemDesc, saleAmount, tax, shipping,
total, currency) {
        sfTrackConvEvent("Lead", "Venue Inquiry", itemDesc);
    }
    function registerEventInquiry() {
        sfTrackConvEvent("Lead", "Event Inquiry", '');
    }
    function registerEventRegistration() {
        sfTrackConvEvent("Lead", "Event Registration", '');
    }
    function registerContactUs() {
        sfTrackConvEvent("Lead", "Contact Us", '');
    }
    function registerNewsletterSignup() {
        sfTrackConvEvent("Signup", "Newsletter Signup", '');
    }
    function registerTheatreInquiry() {
        sfTrackConvEvent("Lead", "Theatre Locator", '');
    }



    /**
    * selector - the jQuery selector string that finds the link
    * eventFunc - the CLEQ event that is triggered
    * trans - do CLEQ transitional tagging
    * transGA - do GA transitional tagging
    */
    function apoTrackEventLink(selector, eventFunc, trans, transGA) {
        var links = $(selector);
        if (links.length) {
            links.each(
			function (index) {
			    var link = $(this);
			    var existingOnClick = link.attr('onclick');
			    //				var existingOnClick = this.getAttribute('onclick');  // had to use getAttribute to read onclick with malformed javascript with extra apostrophe 
			    if (typeof existingOnClick != 'undefined') {
			        if (typeof existingOnClick == 'string') {
			            existingOnClick = new Function(existingOnClick);
			        }
			        if (existingOnClick) {
			            link.attr('onclick', null);
			        }
			    }
			    else {
			        existingOnClick = null;
			    }
			    link.click(
					function (e) {
					    var retVal = true;
					    if (existingOnClick) {
					        retVal = existingOnClick.call(this, e);
					    }
					    if (retVal == undefined || retVal) {
					        if (eventFunc) {
					            eventFunc(this);
					        }
					        if (trans) {
					            //								retVal = conversionTracker.linkClick(this,true);
					            retVal = true;
					            if (retVal) {
					                if (transGA) {
					                    _gaq.push(['_link', link[0].href]);
					                }
					                retVal = false;
					            }
					        }
					    }
					    return retVal;
					}
				);
			}
		);
        }
    }

    /**
    * form - the jQuery selector that finds the form
    * eventFunc - the CLEQ event that is triggered
    * trans - do CLEQ transitional tagging
    * transGA - do GA transitional tagging
    */
    function apoTrackEventFormPost(form, eventFunc, trans, transGA) {
        var existingOnSubmit = form.attr('onsubmit');
        if (typeof existingOnSubmit == 'string') {
            existingOnSubmit = new Function(existingOnSubmit);
        }
        if (existingOnSubmit) {
            form.attr('onsubmit', null);
        }
        form.submit(function (e) {
            var retVal = true;
            if (existingOnSubmit) {
                var retVal = existingOnSubmit.call(this, e);
            }
            if (retVal == undefined || retVal) {
                if (eventFunc) {
                    eventFunc();
                }
                if (trans) {
                    //				retVal = conversionTracker.linkForm(this,true);
                    retVal = true;
                    if (retVal) {
                        if (transGA) {
                            _gaq.push(['_linkByPost', this]);
                        }
                    }
                }
            }
            return retVal;
        });
    }

    function apoTrackEventSelectorPost(selector, eventFunc, trans, transGA) {
        var forms = $(selector);
        if (forms.length) {
            forms.each(function (index) {
                var form = $(this);
                apoTrackEventFormPost(form, eventFunc, trans, transGA);
            })();
        }
    }

    /**
    * selector - the jQuery selector that finds the link
    * preFunc - the function to run before the onclick function
    * postFunc - the function to run after the onclick function
    */
    function regPrePostClickFuncsBySelector(selectors, preFunc, postFunc) {
        if (selectors) {
            selectors.each(
			function (index) {
			    var link = $(this);
			    var existingOnClick = link.attr('onclick');
			    //				var existingOnClick = this.getAttribute('onclick');  // had to use getAttribute to read onclick with malformed javascript with extra apostrophe 
			    if (typeof existingOnClick != 'undefined') {
			        if (typeof existingOnClick == 'string') {
			            existingOnClick = new Function(existingOnClick);
			        }
			        if (existingOnClick) {
			            link.attr('onclick', null);
			        }
			    }
			    else {
			        existingOnClick = null;
			    }
			    link.click(
					function (e) {
					    var retVal = true;
					    if (preFunc) {
					        preFunc(this);
					    }
					    if (existingOnClick) {
					        retVal = existingOnClick.call(this, e);
					    }
					    if (postFunc) {
					        postFunc(this);
					    }
					    return retVal;
					}
				);
			}
		);
        }
    }

    /**
    * selector - the jQuery selector string that finds the link
    * preFunc - the function to run before the onclick function
    * postFunc - the function to run after the onclick function
    */
    function regPrePostClickFuncs(selectorString, preFunc, postFunc) {
        var selectors = $(selectorString);
        return regPrePostClickFuncsBySelector(selectors, preFunc, postFunc);
    }


    function scrapeEventVenue(elem) {
        // scrape the venue information
        var link = $(elem);
        var row = link.parents('tr').first();
        var venueTd = row.children('td:eq(1)');
        //	var venue = venueTd.find('b').text();  	// get name only
        var venue = $.trim(venueTd.html()).replace(/<b>/ig, '').replace(/<\/b>/ig, '').replace(/<br>/ig, ',');   // get name, address, city, state, zip
        registerVenueInquiry(new Date().getTime() + '-' + Math.floor(Math.random() * 9876543),
														venue, 1, 0, 0, 1, null);
    }



    // **************  Fathom Theatre Church  ****************

    function scrapeTheatreVenue(elem) {
        // scrape the theatre venue information
        var link = $(elem);
        var tbody = link.parents('tbody').first()
        var venueName = $.trim(tbody.find('tr:eq(0) td:eq(1) span:eq(0)').text());
        var venueAddr = $.trim(tbody.find('tr:eq(1) td:eq(0)').text());
        var venue = venueName + ';' + venueAddr;
        registerVenueInquiry(new Date().getTime() + '-' + Math.floor(Math.random() * 9876543),
															venue, 1, 0, 0, 1, null);
    }

    function addTagsForMapButtons() {
        // "Map" button click on Theatre-Locator pages
        var theatreMapButtonSelector = $('.Box640Mid:eq(0) a:contains(Map)');
        apoTrackEventLink(theatreMapButtonSelector, scrapeTheatreVenue, false, false);

        // apopost = new Function( jQuery('#ctl18_dlBottomPaging_ctl00_lbPage').attr('href') )
        // add hooks to monitor when ajax reloads the venue list
        regPrePostClickFuncs('#ctl18_panBottomPaging a', theatrePageChanging, theatrePageChanged);
    }

    function theatrePageChanging() {
        $('#ctl18_panBottomPaging').attr('waitForReload', 'yes')
    }

    function waitForTheatrePageChange() {
        if ($('#ctl18_panBottomPaging').attr('waitForReload') != null) {
            setTimeout(waitForTheatrePageChange, 100);
        }
        else {
            addTagsForMapButtons();
        }
    }

    function theatrePageChanged() {
        waitForTheatrePageChange();
    }

    if (document.location.href.indexOf('http://www.fathomtheatrechurch.com/Theatre-Locator') != -1) {
        addTagsForMapButtons();
    }


    var getInTouch = $('.GetInTouch');
    if (getInTouch != null && getInTouch.length > 0) {
        // we're on a page that has a Get in Touch section

        var theatreInquirySelector = '.GetInTouch .zipcodebutton a';
        apoTrackEventLink(theatreInquirySelector, registerTheatreInquiry, false, false); 								// link to form's button

        var contactUsSelector = '.GetInTouch a:contains("Contact Us")';
        apoTrackEventLink(contactUsSelector, registerContactUs, false, false);
        var newsLetterSignUpSelector = '.GetInTouch a:contains("Sign Up for Our Newsletter")';
        apoTrackEventLink(newsLetterSignUpSelector, registerNewsletterSignup, false, false);
    }


});

