// global variables for page rendering
var pageglobal_discount;
var pageglobal_cityid;
var pageglobal_updatefunc;

// set the default User-Agent header for all AJAX requests so we don't generate sessions for web services lookups
$.ajaxSetup({
    beforeSend: function (xhr) {
        xhr.setRequestHeader('User-Agent', 'bot');
    }
});

$(document).ready(function() {
	
	cartNum = cart_contents();
  $('#cart_num').text(cartNum);

	copyDate = new Date().getFullYear();
	$('.copy-date').text(copyDate);
	
	$('.go-btn').click(function() {
		citySel = $('select.sel-city').val();
		if (citySel != "") {
			window.location = citySel;
		}
		else {  
			alert("Please select a city first");
		}
	});
	
	//Open overlay
	$('body').delegate('.open-overlay', 'click', function() {
	//$('.open-overlay').click(function() {
	  ovrClass = $(this).attr('overlay-class');
	  ovrFile = $(this).attr('overlay');
	  openOverlay(ovrClass, ovrFile);
	});
	$('.close-overlay').click(function() { closeOverlay(); });
	
	//Mailing list signup
	$('#mce-EMAIL').focus(function() {
		$(this).attr('value', "");
		$(this).css({color: "#666666"});
	});
  $('#mc-embedded-subscribe').click(function() {
		emailVal = $('#mce-EMAIL').val();
		if (emailVal == "") {
			alert("Email address is required");
			return false;
		}
		else if (isValidEmailAddress(emailVal) == false) {
			alert("Please enter a valid email address");
			return false;
		}
		else {
			$('#form_enews').submit();
		}
	});
	
	//Google translate
	$('.show-translate').click(function() {
		$('.g-translate').hide();
		$('#g_translate').load('/load/google-translate');
	});
	//FB like
	$('#connect_load').load('/load/dom/connect-load');
	$('#verisign_load').load('/load/dom/verisign-load');

  //Offsite links
	$('a[target=_blank]').each(function() {
		$(this).attr('track', $(this).attr('href'));
	});

	//Link click tracking
	$('[track]').click(function() {
		trackLabel = $(this).attr('track');
		//Google
		_gaq.push(['_trackEvent', pageType, trackLabel]);
		//Test & Target
		mboxUpdate('citypass_global', 'act='+trackLabel);
	});
	
	//Cookies + Discount
    var mv_source = $.url.param('mv_source');
    // console.log('mv_source from URL is ', mv_source);

    if (!mv_source && $.url.param('cmpid') && $.url.param('cmpid').match(/^cj$/i)) {
        mv_source = 'CJ';
    }

    // test for commission junction group
    if (mv_source && mv_source.match(/^cj$/i) && $.url.param('group')) {
        mv_source = 'CJ_' + $.url.param('group');
    }

    // set the discount and mv_source cookies if we've newly set the mv_source variable
    if (mv_source) {
        // console.log('mv_source is ', mv_source);
        // Look up the cookie affiliate and the CGI affiliate (if both present), and make
        // them fight for dominance.

        var cookie_mv_source = $.cookie('MV_SOURCE');
        // console.log('cookie MV_SOURCE is ', cookie_mv_source);
        if (mv_source != cookie_mv_source) {
            var cookie_affiliate;
            var mv_source_affiliate;

            // There are complexities in the code which follows, because the requests are asynchronous
            // and we can't set the page referrer notice or the discount information until we know what
            // the affiliate is. So we look up the CGI-specified affiliate, then respond to that request's
            // completion by looking up the cookie-specified affiliate, then respond to THAT completion
            // by determining the winner, and finally do all the post-affiliate processing.
            $.getJSON(
                '/lookup/affiliate/' + mv_source,
                function(data) {
                    // console.log('data from ', mv_source, ' is ', data);
                    mv_source_affiliate = data;
                    if (cookie_mv_source == undefined) {
                        $.cookie('MV_SOURCE', mv_source_affiliate.username, { expires: 90, path: '/', domain: '.citypass.com' });
                        post_affiliate_processing(mv_source_affiliate.username);
                    }
                    else {
                        $.getJSON(
                            '/lookup/affiliate/' + cookie_mv_source,
                            function(data) {
                                // console.log('data from ', cookie_mv_source, ' is ', data);
                                cookie_affiliate = data;

                                // Per the requirements for a two-tier priority, we compare the priorities divided
                                // by 10 first. If there's a tie, then we consider the one's place.
                                var mv_source_priority = mv_source_affiliate.priority;
                                var mv_src_prio10 = Math.floor(mv_source_priority/10);
                                var cookie_priority = cookie_affiliate.priority;
                                var cookie_prio10 = Math.floor(cookie_priority/10);

                                if (mv_source_affiliate.error) {
                                    // console.log('Error looking up source code affiliate');
                                }
                                else if (mv_src_prio10 > cookie_prio10) {
                                    // console.log('cookie is DEFEATED, ', mv_src_prio10, ' to ', cookie_prio10);
                                }
                                else if (mv_src_prio10 < cookie_prio10) {
                                    // console.log('cookie is VICTORIOUS, ', mv_src_prio10, ' to ', cookie_prio10);
                                    mv_source = cookie_affiliate.username;
                                }
                                else if (mv_source.match(/partnerfusion/i) && cookie_mv_source.match(/partnerfusion/i)) {
                                    if (mv_source_priority >= cookie_priority) {
                                        // console.log('cookie LOSES TIE, ', mv_source_priority, ' to ', cookie_priority);
                                    }
                                    else {
                                        // console.log('cookie WINS TIE, ', mv_source_priority, ' to ', cookie_priority);
                                        mv_source = cookie_affiliate.username;
                                    }
                                }
                                else {
                                    // console.log('cookie IS SUPERCEDED');
                                }

                                if (mv_source != cookie_mv_source) {
                                    $.cookie('MV_SOURCE', mv_source, { expires: 90, path: '/', domain: '.citypass.com' });
                                }

                                post_affiliate_processing(mv_source);
                            }
                        );
                    }
                }
            );
        }
    }
    else {
        mv_source = $.cookie('MV_SOURCE');
        if (mv_source) {
            // console.log('cookie is UNCHALLENGED');
            $.getJSON(
                '/lookup/affiliate/' + mv_source,
                function(data) {
                    mv_source_affiliate = data;
                    $.cookie('MV_SOURCE', mv_source_affiliate.username, { expires: 90, path: '/', domain: '.citypass.com' });
                    post_affiliate_processing(mv_source_affiliate.username);
                }
            );
        }
        else {
            // console.log('there is NO AFFILIATE');
        }
    }
	
}); //end document.ready()

function post_affiliate_processing(mv_source, cookie_mv_source) {
    pageglobal_discount = null;
    $.cookie('discount', null, { path: '/' });

    // show any referral in footer
    // console.log('referral is ', mv_source);
    if (mv_source) {
        $('div.referral').html('referral: ' + mv_source);
    }
    else {
        return;
    }

    var discount;
    $.getJSON(
        '/lookup/discount/' + mv_source,
        function(data) {
            var discount = data[mv_source];

            if (typeof discount == "undefined")
                return;

            // calculate the current time plus 10 hours in the local TZ offset
            var later = new Date((new Date()).getTime() + 1000 * 60 * 60 * 10 );

            $.cookie('discount', JSON.stringify(discount), { expires: later, path: '/' });

            // Set this global in the AJAX handler as well as
            // below, as the discount cookie parsing takes place
            // on the initial load of the page, but this handler
            // may (will) run after that parsing process has
            // occurred.  This prevents the updated
            // pageglobal_discount from being seen on the first
            // page load with a new mv_source field.  We thus
            // utilize a stored reference to any specific page
            // functions to re-invoke after the discount cookie
            // has been setup.

            pageglobal_discount = discount;

            if ($.isFunction(pageglobal_updatefunc))
                pageglobal_updatefunc.call();

            update_discountable_elements();
            discount = $.cookie('discount');
            if (discount) {
                pageglobal_discount = JSON.parse(discount);
                update_discountable_elements();
            }
        }
    );
}

function update_discountable_elements() {
    if (pageglobal_discount) {
        $('.discountable').each(
            function(){
                var price   = $(this).data('price');
                var percent = pageglobal_discount['discount_percent'];
                var format  = $(this).data('format');

                if (!percent || !format)
                    return;

                $(this).html($.sprintf(format, price * (100 - percent) / 100));
            }
        );
    }
}


//Overlay boxes
function openOverlay(ovrC, ovrF) {
 	closeOverlay();
 	$('#tbl_overlay').appendTo('#page').addClass(ovrC).fadeIn();
	$('#overlay_content').load(ovrF);
	return false;
}
function closeOverlay() {
	if ($('#tbl_overlay').hasClass('ovr-stay')) {
		$('#overlay_content').contents().hide().appendTo('body');
	}
	$('#tbl_overlay').hide().appendTo('body').attr('class', '');
	$('#overlay_content').html('');
}

function cart_contents() 
{
    /* Return the number of items in the cart according to the cart contents cookie. */

    var cookie_name = 'CART_CONTENTS';
    if (document.cookie.length > 0) {
        var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );
        if (results) {
            return unescape(results[2]);
        }
        else {
            return 0;
        }
    }
    return;
}

//Validate Email
function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}

