$(document).ready(function() {
    var page = location.href;
    
    //if you page requires validation
    if(page.search("catalogrequest.php") != -1){
        validateForm();
    } 
	
	if(page.search("giftregs.php") != -1){
		createProductModals();		
	}
	
	if(page.search("trailwingiftcard.php") != -1){		
		$("#submit").click(function(){
			if($("#country").val() == ""){
				alert("Please select a country");
				return false;				
			}else{
				return true;				
			}
		});		
	}
	/*
	//check for free shipping countdown	
	var freeShippingStart = readCookie('freeShippingStart');
		//check for free shipping coundown thingy
	if(freeShippingStart !== null){		
		setInterval(tickShippingClock, 1000);
	}else{
		//are they coming from another site?		
		try{
			var ref = document.getElementById("refferURL");
			var reffer = ref.innerHTML;			
			if(reffer.search("cruelgirl") != -1 || reffer.search("rockiesjeans") != -1){
				var now = new Date();		
				createCookie("freeShippingStart", now.getTime(), 1000);
				setInterval(tickShippingClock, 1000);			 	
			}else if(reffer.search("cinchjeans") != -1 ){
				var now = new Date();				
				createCookie("freeShippingStart", now.getTime(), 1000);
				setInterval(tickShippingClock, 1000);													
			}	
		}catch(e){}		
	}*/
		   
});
/*
function tickShippingClock(){
	var now = new Date();
	var then = readCookie("freeShippingStart");
	if(then !== null){		
		var start = Number(then);		
		var seconds = Math.round((now - start)/1000);
		
		var hoursLeft = 3 - Math.floor(seconds/3600);
		var minutesLeft = 60 - (Math.floor(seconds/60)%60);
		var secondsLeft = 60 - (seconds%60);
		
		var timeStr = hoursLeft+":"+PadDigits(minutesLeft,2)+":"+PadDigits(secondsLeft, 2);
		
		if(seconds >= 14400){			
			eraseCookie("freeShippingStart");
			jQuery("#shippingTimer").slideUp();								
		}else{
			jQuery("#shippingTimer > #time").html(timeStr);
			jQuery("#shippingTimer").show();			
		}		
	}else{
		return;
	}	
}*/

function createProductModals(){
	$(".modalProduct").click(function(){
		//pull out the product ID
		var productID = $(this).attr("class");
		productID = productID.split(" ");
		productID = productID[1];		
		
		$.ajax({
			data: "productID="+productID,
			url: "jax/registryProductJax.php",
			dataType: "json",
			success: function(product){		
				var productcode = product.productcode.replace("-", "").substr(0,6);
				var image = "images/P/"+productcode+".jpg";
				var html = "<img id=\"modalImage\" src=\""+image+"\"/>";
				html += "<div id=\"modalTitle\">"+product.product+"</div>";
				html += "<div id=\"modalDescription\">"+product.descr+"</div>";
				
				//load the content into the modal
				$("#productModalContent").html(html);
				//show content when ready
				$("#modalImage").load(function(){					
					//show all the cool stuff
					$("#productModalContent").show();
					$("#modalLoadImg").hide();
				
					//get the positioning right
					var jqwindow = $(window);
					var windowHeight = jqwindow.height();
					var padding = 100 + jqwindow.scrollTop();
					$(".productModalStyle").css("top", padding);			
				});
			}			
		});
		
		//finally open the dialog on the click and escape any page reload
		$("#productModal").dialog( 'open' );
		$(".ui-widget-overlay").css("left", 0);
		return false;		
	});
	
	$("#productModal").dialog({
		autoOpen: false,
		dialogClass: "productModalStyle",
		resizable: false,
		draggable: false,
		modal: true,
		open: function(){
			$(".ui-widget-overlay").css("opacity", "0.8");
		},
		close: function(){
			$("#modalLoadImg").show();			
			$("#productModalContent").hide();
			$("#productOverlay").hide();
		}								
	});
		
	$(".ui-dialog-titlebar-close").remove();
	$("#productModalClose").click(function(){
		$("#productModal").dialog("close");
	});
	
}

function validateForm(){	
	
    var labelColor = $("label").css("color");
                    
    //check all the validated fields after you enter something in them           
    $(".alphaNumeric").blur(function(){
        element = $(this);
        var id = element.attr("id");
        //get the corresponding label for this element
        var label = $("label[for="+id+"]");
                        
        //call the validation function for this type and allow blanks if they should be
        var isValid = validAlphaNumeric(this, element.hasClass("blankOK"));          
            
        //let the user know it is wrong            
        if(!isValid){
            label.css("color", "red");
        }else{
            label.css("color", labelColor);
        }            
    });        
    $(".zipField").blur(function(){
        element = $(this);
        var id = element.attr("id");
        //get the corresponding label for this element
        var label = $("label[for="+id+"]");                        
        //call the validation function for this type and allow blanks if they should be
        var isValid = validZip(this, $(this).hasClass("blankOK"));            
        //let the user know it is wrong            
        if(!isValid){
            label.css("color", "red");
        }else{
            label.css("color", labelColor);
        }                
    });        
    $(".emailField").blur(function(){
        element = $(this);
        var id = element.attr("id");
        //get the corresponding label for this element
        var label = $("label[for="+id+"]");                        
        //call the validation function for this type and allow blanks if they should be
        var isValid = validEmail(this, $(this).hasClass("blankOK"));           
        //let the user know it is wrong            
        if(!isValid){
            label.css("color", "red");
        }else{
            label.css("color", labelColor);
        }                        
    });        
    $(".selectBox").change(function(){
        element = $(this);
        var id = element.attr("id");
        //get the corresponding label for this element
        var label = $("label[for="+id+"]");                        
        //call the validation function for this type and allow blanks if they should be
        var isValid = selectValidation(this);
        //let the user know it is wrong            
        if(!isValid){
            label.css("color", "red");
			
        }else{
            label.css("color", labelColor);
        }            
    });          
        
    //when submit is clicked check all teh validated fields
    $("#submit").click(function(){
        var valid = true;
        
        $(".validatedField").each(function(){$(this).triggerHandler('blur');});
        $(".selectBox").triggerHandler('change');
        
        $(".validatedField").each(function(){
            var id = $(this).attr('id');
            var label = $("label[for="+id+"]");
            if(label.css("color") != labelColor){
                valid = false;        
            }
        });
        
        if(!valid){
            $('.formErrorMessage').html("Some the data you have entered is incorrect.<br/>Please review the fields labeled in red.");
	        return false;
        }
    });
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' '){
            c = c.substring(1, c.length);
        }
        if (c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length, c.length);
        }
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

function PadDigits(n, totalDigits) 
    { 
        n = n.toString(); 
        var pd = ''; 
        if (totalDigits > n.length) 
        { 
            for (i=0; i < (totalDigits-n.length); i++) 
            { 
                pd += '0'; 
            } 
        } 
        return pd + n.toString(); 
    }