// global variables for page rendering
var pageglobal_discount;
var pageglobal_cityid;
var pageglobal_updatefunc;
var dualProduct;
var cityId;
var attId;
var cityName;

WebFont.load({
	google: {
  	families: [ 'Cantarell', 'Droid Sans' ]
  }
});

// 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() {

  $('body.product').each(function() {
    pageglobal_cityid = this.id;
    return false;
  });

	$('div#reviews_recent').hide();

  cartNum = cart_contents();
  $('#cart_num').text(cartNum);

	copyDate = new Date().getFullYear();
	$('.copy-date').text(copyDate);

	cityId = $('body').attr('id');
	cityName = $('#city_name_holder').text();
	attId = $('#att_id_holder').text();

	//Blank more links
	$('a.more-blank').text("");

	//Image rollover
	$('.roll').hover(function() {
    var curImg = $(this).attr('src');
    $(this).attr('src', $(this).attr('hover'));
    $(this).attr('hover', curImg);
   }, function() {
    var curImg = $(this).attr('src');
    $(this).attr('src', $(this).attr('hover'));
    $(this).attr('hover', curImg);
  });

	//Buy forms
	$('select.qty-tkt').attr('value', 0);

	$('select.qty-tkt').change(function() {
		if ( $(this).val() == "more" ) {
	  	selId = $(this).attr('id');
			$(this).prev('.lbl-qty').hide();
			$(this).next('.custom-sel').hide();
			$(this).next().prepend('Enter ');
	  	$(this).after('<input class="qty-tkt" type="text" id="'+selId+'" name="'+selId+'" value="" />').remove();
			$('#'+selId).focus();
	  }
	});


	$('#buyform .addbtn').click(function() {
        if ( ($('#buyform .a-tkt').val() == 0) && ($('#buyform .y-tkt').val() == 0) ) {
            alert("You must select a quantity");
            return false;
        }
        if ($('input#adult').length) $('input#adult').val($('input#adult').val().replace(/[^0-9]/g,''));
        if ($('input#youth').length) $('input#youth').val($('input#youth').val().replace(/[^0-9]/g,''));
        if ( ($('#buyform .a-tkt').val() == undefined || $('#buyform .y-tkt').val() == undefined)
          && !$.trim($('input#adult').val()).length && !$.trim($('input#youth').val()).length ) {
            alert("You must input a quantity");
            return false;
        }
        return true;
	});
	$('#buyform2 .addbtn').click(function() {
		if ( ($('#buyform2 .a-tkt').val() == 0) && ($('#buyform2 .y-tkt').val() == 0) ) {
	  	alert("You must select a quantity");
	    return false;
	  }
	});
	
	//Pluck Reviews Clicks + Submits	
	$('.show-reviews').click(function() {
		$('#t_reviews').click();
		location.href="#detail_tabs";
	});
	$('.btn-write-review').click(function() {
		checkReviewLogin();
	});
	$('.toggle-review-login').click(function() {
		$('.reviews-login-area').hide();
		$($(this).attr('show')).show();
	});
	 
		//reviews login
	$('#btn_review_create_account').click(function() {
		em = isValidEmailAddress($('#review_create_email').val());
		p1 = $('#review_create_password').val();
		p2 = $('#review_create_password_confirm').val();
		if (em == false) {
			alert("You must enter a valid email address.");
		} else if ( p1 != p2 ) {
			alert("Passwords do not match.  Please re-enter.");
			$('#review_create_password').val('');
			$('#review_create_password_confirm').val('');
		} else {
			$('#review_create').submit();
		}
	});
	$('#review_create').submit(function() {
		$.ajax({
			type: "POST",
			url: "/citytraveler/auth_citypass/create",
			data: $('#review_create').serialize(),
			dataType: "json",
			success: function() {
				checkReviewLogin();
			},
			error: function(response) {
				eTxt = jQuery.parseJSON(response.responseText).error;
				$('#review_create_response').addClass('login-error').show();
				$('#review_create_response').html(eTxt);
			}
		});
		return false;
	});
	$('#review_login').submit(function() {
		$.ajax({
			type: "GET",
			url: "/citytraveler/auth_citypass/login",
			data: $('#review_login').serialize(),
			dataType: "json",
			success: function() {
				checkReviewLogin();
			},
			error: function(response) {
				eTxt = jQuery.parseJSON(response.responseText).error;
				$('#review_login_response').addClass('login-error').show();
				$('#review_login_response').html(eTxt);
			}
		});
		return false;
	});
	$('#review_forgot').submit(function(){
  	var email = $('input#review_forgot_email').val();
    if (!isValidEmailAddress(email)) {
			alert("You must enter a valid email address.");
    }
      else {
          $.ajax({
              type: "GET",
              url: "/citytraveler/auth_citypass/remind",
              data: $('form#review_forgot').serialize(),
              dataType: "json",
              success: function(data, textStatus, response) {
                  eTxt = jQuery.parseJSON(response.responseText).msg;
                  $('#review_forgot_response').show().html(eTxt);
              },
              error: function(response){
                  eTxt = jQuery.parseJSON(response.responseText).error;
                  //console.log('response error: ', eTxt);
                  $('#review_forgot_response').addClass('login-error').show().html(eTxt);
              }
          });
      }
      return false;
  });
	
	//Tabs
	$('#detail_tabs li').click(function() {
		$('#detail_tabs li').removeClass("active");
		$(this).addClass("active");
		tabId = $(this).attr('id');
		if ((tabId == 't_map') && (map_is == false)) {
			loadMap();
			map_is = true;
		}
		tabId = tabId.replace('t_', 'tab_');
		$('.tab-content').hide();
		$('#'+tabId).show();
	});
	//Subtab menu
	$('.sub-tab-row li').click(function() {
		$('.sub-tab-row li').removeClass("active");
		$(this).addClass("active");
		tabId = $(this).attr('id');
		tabId = tabId.replace('s_', 'subtab_');
		$('.subtab-content').hide();
		$('#'+tabId).show();
	});
	
	//Map
	
	//Populate directions selects
	$('.map-att').each(function() {
		attLbl = $(this).children('label').text();
		if (attLbl == '') { 
			attLbl = '&nbsp;&nbsp;*';
			attNm = $(this).text();
		} else {
			attNm = $(this).text().substr(1);
		}
		$('.dir-sel').append('<option value="'+ $(this).attr('marr') +'">'+ attLbl + '. '+ attNm + '</option>');
	});
	
	//Add custom address(es)
	$('.dir-txt').val('Enter address');
	
	$('.show-txt').click(function() {
		$(this).parent().siblings('.dir-sel').hide().val('');
		$(this).parent().siblings('.dir-txt').show();
		$(this).hide();
		$(this).siblings('.show-sel').show();
	});
	$('.show-sel').click(function() {
		$(this).parent().siblings('.dir-txt').hide().css({ color: "#848484" }).val('Enter address');
		$(this).parent().siblings('.dir-sel').show();
		$(this).hide();
		$(this).siblings('.show-txt').show();
	});
	$('.dir-txt').focus(function() {
		$(this).val('').css({ color: "#000000" });
	})
	
	//Refresh Map
	$('.map-ref').click(function() {
		$('#route_holder').hide();
		loadMap();
	});

	//Open overlay
	$('.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();
		}
	});

	//FAQ
	$('.faq-list li').addClass("q-closed");
	$('.faq-list li:first').removeClass("q-closed");

 	$('.question').click(function() {
		if ( $(this).parent().hasClass("q-closed") ) {
			$(this).parent().removeClass("q-closed");
		}
		else { 
			$(this).parent().addClass("q-closed");
		}
	});

	//Select city Buy (Home)
	$('.select-buy').click(function() {
		citySel = $('#select_city').val();
		if (citySel != "") {
			window.location = citySel;
		}
		else {  
			alert("Please select a city first");
		}
	});
	
	//Language Chooser
	langHost = $.url.attr('host');
	$('#sel_language li[lang-url='+langHost+']').show();
	
	$('#sel_language li').click(function() {
		if ($(this).hasClass('lang-closed')) {
			$('#sel_language li').removeClass('lang-closed').addClass("lang-open").show();
			$('#language_choose').addClass('lang-shadow');
		} else if ($(this).hasClass('lang-other')) {
			$('#sel_language').hide();
			$('#language_choose').addClass('showing-google').addClass('lang-shadow');
			$('#language_google').load('/load/google-translate-head');
		} else {
			langUrl = $(this).attr('lang-url');
			OneLink(langUrl);
		}
	});

	//Google translate
	$('.show-translate').click(function() {
		$('#translate_msg').hide();
		$('#g_translate').load('/load/google-translate');
	});
	//FB like, google +1
	$('#connect_load').load('/load/dom/connect-load');

	//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');
        }
    }

//Moovweb hacks
  /* remove new text from cart number link area */
var mvNum = $('div.mvCartNum');
$('.mv-tag #head_cart_msg').text("").append(mvNum);

  /* combined price styling */
$('.mv-tag div.combined').css({ "padding-top": "2px", "background": "#000", "color": "#FFF", "text-align": "center", "font-family": "Cantarell, serif", "font-size": "15px" });

  /* Footer */
$('.mv-tag div.social-area').remove();

});

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));
            }
        );
    }
}

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;
}

//JW Player
function initVideo(vidFile, vidThumb, playerTitle, vidTitle, vidWidth, vidHeight, vidAuto, vidStart) {
	jwplayer('video_player').setup({
    flashplayer: '/js/jwplayer/player.swf',
    file: vidFile,
    image: vidThumb,
    width: vidWidth,
		height: vidHeight,
    id: playerTitle,
		title: vidTitle,
		author: 'CityPASS',
		stretching: 'fill',
    controlbar: 'bottom',
    dock: 'true',
		backcolor: '000000',
		screencolor: 'ffffff',
		frontcolor: 'ffffff',
		autostart: vidAuto,
    start: vidStart,
		icons: false,
		plugins: {
			gapro: { accountid: 'UA-531856-1' }
		}
  });
  thePlayerName = playerTitle;
  videoTitle = vidTitle;
}

//Review Login
function checkReviewLogin() {
	if ($.cookie('at') == null) {
		$('#reviews_login').show();
	} else {
		rUrl = $.url.segment(0);
		if (rUrl == 'california') { rUrl='southern-california'; }
		window.location.assign("/"+rUrl+"?plckReviewCreate=true");
	}
}

function pluckReviewDom() {
	$('p.pluck-review-full-reviewer-name-reviews').prepend('by ');

	$('.pluck-review-full-stars .pluck-review-starsOutput').each(function() {
		thisRate = $('em.rating', this).text();
		$(this).addClass('rate-'+thisRate);
	});
	$('a.pluck-review-full-reviewer-name').each(function() {
		$(this).removeAttr('href');
	});
	$('div.pluck-review-full-review-single-review-wrap').each(function() {
		thisRev = $('div.pluck-review-full-reviewer-block', this);
		$('p.pluck-review-full-review-title', this).after(thisRev);
	});
	
	rListId = '#'+$('div.pluck-review-list').attr('id');

	$('span.pluck-review-full-review-has-comments').each(function(i) {
		commNum = $('.pluck-review-full-review-comment-count', this).text();
		if (commNum != '0') {
			$(this).click();
		}
	});
}

function pluckCommentsDom() {
	$('.pluck-comm').each(function() {
		commId = '#'+$(this).attr('id');
		$('.pluck-comm-comment-input', commId).addClass("comm-move-bottom").appendTo(commId);
	})
}

//Overlay boxes
function openOverlay(ovrC, ovrF) {
 	closeOverlay();
 	$('#tbl_overlay').appendTo('#frame').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 dualOverlay() {
  $('#tbl_overlay').appendTo('#frame').addClass('ovr-dual-product').fadeIn();
  $('#overlay_content').load('/load/dual/'+cityId+'-dual-overlay');
}

//Google Map
function loadMap() {
  var script = document.createElement("script");
  script.type = "text/javascript";
  script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initMap";
  document.body.appendChild(script);
}

//Look Inside
function lookInside(bookletClass, bookletPages) {
	bPages = bookletPages;
	openOverlay(bookletClass, '/load/booklet-inside');
}

//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);
}

//Language chooser
function OneLink(sHostname) {
    document.location.href = document.location.protocol + "//" + sHostname + document.location.pathname;
}

