var GearBag = [];
var playerPassProduct = 0;
var badLatinChars = new Array('%C3%80','%C3%81','%C3%8D','%C3%83','%C3%88','%C3%89','%C3%96','%C3%9C','%C3%91');	//'À','Á','Í','Ã','È','É','Ö','Ü','Ñ'
var goodLatinChars = new Array('%C0','%C1','%CD','%C3','%C8','%C9','%D6','%DC','%D1');	//'','','','','','','','',''

if(typeof Get_Cookie == 'function') { 
	var clubCookie = Get_Cookie('Club');
	//alert('clubCookie: '+clubCookie);
}

if(typeof(siteUrl)==="undefined"){
	var siteUrl=setSiteUrl();
}
	
$(document).ready(function(){
$.ajaxSetup ({
    // Disable caching of AJAX responses
    cache: false
});

if(typeof heroBaseNumber !=="undefined"){
	preload(['images/Catalog/ProductImages/image_exists_gb.php?sku='+heroBaseNumber, siteUrl+'/productShot/images/checkout.png']);
}

if(typeof productImageArray !=="undefined"){
	preload(productImageArray);
}

var cViewVal = $('#ClassicView').val();
var gcAmountVal = $('#giftcard_amnt').val();
if(typeof(cViewVal) !=='undefined' || typeof(gcAmountVal) !== "undefined"){
	$("#buyNow").fadeTo(1,1);
} else {
	if(typeof(updateBuyButton)==="function"){
		updateBuyButton();
	} else {
		$("#buyNow").fadeTo(1,1);
	}
}
	
	var teamCust = $('input:radio[name=bundle-customization]:checked').val();
	var in_process=0;
	var this_product;
	var next_product;
	var prev_product;
	
	$(window).load(function(){
		updateRunningGearBag();
	});
	
	$(window).scroll(function(){
		if($(this).scrollTop() > 80){
			$(".tb_bnr").slideDown();
		} else {
			$(".tb_bnr").slideUp();
		}
		
		// if ($(this).scrollTop() > 800 && modalShown==0) {
			// showGoalClubModal();
		// }
	});
	
/*----- BuyNow Button Updateing -----------*/
	var cViewVal = $('#ClassicView').val();
	var gcAmountVal = $('#giftcard_amnt').val();
	if(typeof(cViewVal) !=='undefined' || typeof(gcAmountVal) !== "undefined"){
		$("#buyNow").fadeTo(1,1);
	} else {
		if(typeof(updateBuyButton)==="function"){
			updateBuyButton();
		} else {
			$("#buyNow").fadeTo(1,1);
		}
	}
	
	$("input, select").live('change', function() {
		if(typeof cViewVal==='undefined' && typeof gcAmountVal==='undefined'){
			updateBuyButton();
		}
	});
	
/* ------------------------------------ */
	
/* 	$(".productImg").each(function () {
		var base_arr=$(this).attr('id').split('|');
		var img='images/catalog/productimages/image_exists_2.php?d=2&sku='+base_arr[0]+'&ppvsku=1&zid='+base_arr[1]+'&tid='+base_arr[2]+'&colorway='+base_arr[3];
		//$(this).attr('src', img);
		if((typeof this.naturalWidth != "undefined" && this.naturalWidth == 0 ) || this.readyState == 'uninitialized' ) {
			$(this).attr("src", img);
		}
	});  */

	$(".clickToOrder").click(function(){
	var product_page=false;
	var show_next_prev=($(this).parent().hasClass('ppProduct'));
	playerPassProduct=show_next_prev;
		if($(this).hasClass('similar')){
			var id=$(this).attr('id');
			showProductPageQuickView(id);
		} else {
			var id=$(this).parent().attr('id');
			showQuickView(id, show_next_prev);
		}
		
	});	
	
	$(".clickToOrderList").click(function(){
		var id=$(this).parent().parent().attr('id');
		var show_next_prev=($(this).parent().parent().hasClass('ppProduct'));
		playerPassProduct=show_next_prev;
		showQuickView(id, show_next_prev);
	});	
	
	
	$("#orderModalClose").live('click',function(){
		$("#orderModal, #mask, #jsConf").fadeOut('fast');
		playerPassProduct=0;
		updateRunningGearBag();
	});
	
	$("#confClose").live('click',function(){
		updateRunningGearBag();
		$("#jsConf").fadeOut('fast');
		in_process=0;
		showQuickView(this_product);
		$("#jsConf>p").html();
	});
	
	$("#next").live('click',function(){
		showQuickView(next_product, 'true');
	});
	
	$("#prev").live('click',function(){
		showQuickView(prev_product, 'true');
	});
	
	$(".number, #qty").live('keyup',function(){
		scrubNumber($(this));
	});
	
	$(".name").live('keyup',function(){
		scrubLetter($(this));
	});
	
	$("#ajaxPost, #buyNow").live('click', function(e){
		var valid;
		var gcAmount = $('#giftcard_amnt').val();
		
		var id = $(this).attr('id');
		if(in_process){
			return false;
		}
		
		if(gcAmount!=null) {
			valid = validate_GiftCardForm();
		} else if (clubCookie!='' && clubCookie!=null && virtClubProd==1) {
			valid = ValidateCustomizationNew($('#qty'), true);
		} else {
			valid = validateOrderForm($('#qty'), true);
		}
		
		if(valid===false) {
			e.preventDefault();
			return false;
		}
		/* Doing these again in case of cut and paste. */
		
		$(".number").each(function(){
			scrubNumber($(this));
		});
			
		$(".name").each(function(){
			scrubLetter($(this));
		});
		
		var action = $("#order-form").attr('action');
		var cleanSerializedForm = serializeForm();
		
		if(id=='buyNow'){
			$("body").addClass("wait");
			addToGearBag(cleanSerializedForm, action);	
		} else {
			//in_process=1;
			$("body").addClass("wait");
			var pname=$("#centerDataCol>div>h1").text();
			$.ajax({type: 'GET',
					url: action, 
					data: cleanSerializedForm+"&WL_AddToBasket.x=1&WL_AddToBasket.y=1&ajax=add",
					contentType: 'application/x-www-form-urlencoded',
					dataType: 'script',
					scriptCharset: 'ISO-8859-1',
					success: function(msg) {
						getCallback(msg, pname);
					}				
			});		
		}		
		return false;
	});
	
	$("#gbLeftCol, #tbCheckout").click(function(){
		var url = siteUrl+'/OMBasketManager.process?RestartFlow=t&OMAction=Default';
		//alert(url);
		window.location=url;
	});
	
	$("#gbInfo").click(function(){
		if($(this).parent().hasClass('gbBig')){		
		} else {
			if(GearBag.GBItems > 0){
				//$(this).css( 'background', 'url("/productShot/images/gb-bg-lg.png") no-repeat scroll 0 0 transparent').addClass('gbBig');
				$(this).html('<img src="/productShot/images/ajax-loader.gif" />')
				populateLargeGearBag();
				}
		}
	});
	
	function serializeForm(){
		var badStartPos = null;
		var formData = $("#order-form").serialize();
		// Correct any bad latin characters
		for(var i=0; i<badLatinChars.length; i++) {
			badStartPos = formData.indexOf(badLatinChars[i]);
			if(badStartPos!=-1) {
				var badString = badLatinChars[i];
				var goodString = goodLatinChars[i];
				formData = formData.replace(new RegExp(badString, "g"), goodString);
			}
		}
		return formData;
	}
	
	function scrubNumber(elem){
		var Regex = new RegExp("^[0-9]+$");
		var v = elem.val();
		if( !v.match( Regex ) ) {
			newText = new Array(v.length);
			for (i=0; i<newText.length; i++) {
				if(v.charAt(i).match( Regex )) {
					newText[i] = v.charAt(i);
				}
			}
			newValue = newText.join('');
			elem.val(newValue);
		} else {
			elem.val(v);
		}
	}
	
	function scrubLetter(elem){
		var Regex = new RegExp("^[A-Za-z .'\u00C0\u00C1\u00C8\u00C9\u00CD\u00D6\u00DC\u00D1-]+$");
		var v = elem.val();
		if( !v.match( Regex ) ) {
			newText = new Array(v.length);
			for (i=0; i<newText.length; i++) {
				if(v.charAt(i).match( Regex )) {
					newText[i] = v.charAt(i);
				}
			}
			newValue = newText.join('');
			elem.val(newValue);
		} else {
			elem.val(v);
		}
	}
	
	function getCallback(msg, pname){
		center($("#jsConf"));
		if(msg.indexOf("SUCCESS") != -1){
			updateLastAddedGearBag(msg);
			// $("#jsConf>p").html($("#qty").val()+' '+pname+' '+(parseInt($("#qty").val())>1?'have':'has')+' been added to your to <a href="/OMBasketManager.process?RestartFlow=t&OMAction=Default">Gear Bag</a>.');
			// $("#jsConf").fadeIn('fast');
			//showQuickView(this_product);
			} else {
				$("#jsConf>p").html('There was an error adding '+pname+' to Gear Bag.');
				$("#jsConf").fadeIn('fast');
			}
		$(":input").each(function(){
			//$(this).attr('disabled', 'disabled');
		});
		$("body").removeClass("wait");
	}
	
	function center(elem) {
		elem.css("position","absolute");
		var modal_top = Math.max(( $(window).height() - elem.height() ) / 2+$(window).scrollTop(), 30);
		elem.css("top", modal_top + "px");
		elem.css("left", ( $(window).width() - elem.width() ) / 2+$(window).scrollLeft() + "px");		
	}
	
	function showQuickView(pid, show_next_prev){
		if(typeof(show_next_prev)==="undefined"){ show_next_prev=true; }
		this_product=pid;
		$("#mask").css('height',$(document).height());
		$("#mask").css('filter', "alpha(opacity=40)");
		$(".pn_nav").show();
		$("#prevNext").hide();
		
		var current;
		var pbArray = $('.ppProduct');
		
		
			for(var i=0;i<pbArray.length;i++){
				if($(pbArray[i]).attr('id')==pid){
					current=i+1;
					prev_product=(i>0 ? $(pbArray[i-1]).attr('id') : 0);
					next_product=(i<(pbArray.length-1) ? $(pbArray[i+1]).attr('id') : 0);
				}
			}
		

		$("#count").html(current+' of '+pbArray.length);
		$("#modalContainer").html('<div id="innerWait">Please&nbsp;<img src="'+siteUrl+'/images/large_loader.gif" />&nbsp;Wait.</div><div style="clear: both"></div>');
		center($("#orderModal"));
		$("#orderModal, #mask").fadeIn('slow');
		
		$("#modalContainer").load(siteUrl+'/ProductData.process?&Merchant_Id=1&Product_Id='+pid, function(){
			
			$("#availability").hide(); // hide the "Check Availability link
			$("#qty").attr("maxlength", "2");
			$("#required_status").load(siteUrl+'/ajax/checkRequiredSku.php5?bn='+$("#base_number").text());
			if(playerPassProduct==1){
				/* Click the 'Yes' radio */
				$('input[name=bundle-customization]:eq(0)').click();
				$("#bundle-options").hide();
			}
			/* Get rid of the order form button. */
			// $("#buyNow").remove();
			// /* Add an ajax button. */
			// $("#purchase")
				// /*.css({float: 'none', margin: '0 0 0 20px'})*/
				// .append('<div id="ajaxPost"><img src="/images/soccer/productpage/buttons/buy_now_btn.png" /></div>');
			
			if(next_product==0){
				$("#next").hide();
			}
			if(prev_product==0){
				$("#prev").hide();
			}
			if( show_next_prev ){
				$("#prevNext").show();
			}
			$("#availability").hide(); // hide the "Check Availability link

		});	
	}
	
	function showProductPageQuickView(pid){
		$("#mask").css('height',$(document).height());
		$("#mask").css('filter', "alpha(opacity=40)");
		$("#modalContainer").html('<div id="innerWait">Please&nbsp;<img src="http://staging.soccer.com/images/large_loader.gif" />&nbsp;Wait.</div><div style="clear: both"></div>');
		center($("#orderModal"));
		$("#orderModal, #mask").fadeIn('slow');
		
		$("#modalContainer").load(siteUrl+'/productShot/productDataFrame.php5?pid='+pid, function(){

		});
	}
});
// END document.ready

function populateLargeGearBag(){
	$("#runningGearBag").addClass('gbBig');
	$("#gbInfo").html('');
	$("#gbInfo").load(siteUrl+'/Templates/OM/AjaxGearBagTbl.tem?r=' + myTimestamp(), function(){
		var ht=$("#RunningGearbagContainer").height();
		var wd=$("#RunningGearbagContainer").width()+140;
		$("#runningGearBag").animate({width:wd+'px', height: ht+'px'}, 200);
		$("#runningGearBag").delay('3000').animate({width:'146px', height: '24px'}, 200, function(){	
			$("#gbInfo").hide();			
			updateRunningGearBag();
			$(this).removeClass('gbBig');
		});
	});
}

function addToGearBag(post, action){
	$("#runningGearBag").addClass('gbBig');
	$.ajax({type: 'GET',
			url: action, 
			data: post+"&WL_AddToBasket.x=1&WL_AddToBasket.y=1&ajax=add&r=" + myTimestamp(),
			success: function(msg) {
				updateLastAddedGearBag(msg);
				$("#orderModal").fadeOut('fast');
				$("#mask").fadeOut('fast');
				$("body").removeClass('wait');
			}				
	});	
}

function preload(arrayOfImages) {
	$(arrayOfImages).each(function () {
		$('<img />').attr('src',this).appendTo('body').hide();
	});
}

function updateRunningGearBag(){
	var data;
	GearBag = [];
	$.getJSON(siteUrl+'/Templates/OM/jsonGBData.tem?r=' + myTimestamp(), function(data) {
		GearBag = data;		
		if(GearBag.GBItems == 0){ GearBag.GBSubTotal = "0.00"; }
		$("#gbInfo").html('<span id="gbItems">'+GearBag.GBItems+'</span> Item'+(GearBag.GBItems==1?'':'s')+' | $<span id="gbSubTotal">'+GearBag.GBSubTotal+'</span>').fadeIn('fast');
		$("#runningGearBag").fadeIn('fast');
		if(GearBag.GBItems>0){
			$("#tbCheckout").fadeIn('fast');
		} else {
			$("#tbCheckout").hide();
		}			
	});
}

function updateLastAddedGearBag(msg){
	$("#gbInfo").html(msg);
		var ht=$("#RunningGearbagContainer").height();
		var wd=$("#RunningGearbagContainer").width()+140;
		$("#runningGearBag").animate({width:wd+'px', height: ht+'px'}, 200);
		$("#runningGearBag").delay('2000').animate({width:'146px', height: '24px'}, 200, function(){	
			$("#gbInfo").hide();			
			updateRunningGearBag();
			$(this).removeClass('gbBig');
		});
}

function myTimestamp(){
    tstmp = new Date();    
    return tstmp.getTime();
} 

function setSiteUrl(){
	var host = (document.location.host.indexOf('espanol.soccer.com') == -1 ? 'http://'+document.location.host : 'http://espanol.soccer.com/soccer/enes/24/_www_soccer_com/');
	return host;
}
