// JavaScript Document

$(document).ready(function() {
						   
	// NAVIGATION - active	
	$('.navigation ul li a').each(function() {
		if(this.href == window.location) {
			$(this).parents("li").addClass("current");	
		}
	});
		   
	// NAVIGATION
	$('.navigation ul li').hover(function() {
		$(this).find('ul').show();
		$(this).addClass('active');
		}, function() {
		$(this).find('ul').hide();
		$(this).removeClass('active');
	});

	// Update cart count
	$('#cart_count').load('/cart/count');	
	
	// IE SELECT MENU
	if($.browser.msie){
		$('select.event-home').focus(function(){
			$(this).css({'width':'auto'});
		});
		
		$('select.event-home').blur(function(){
			$(this).css({'width':'250px'});
		});
	 }
	
	// product uniform height
	if($(".products").length>0){ 
	var tallest = 0;
		$(".products .bucket").each(function() {
			if($(this).height()>tallest) { tallest = $(this).height(); }
		});
		$(".products .bucket").css({height:tallest});
	}
	
	// change items per page
	$("select.changelimit").change(function() {
        var val = $(this).val();
        if (val != '') {
            location.href= val;
        }
    });
    
    // change certain button text when loading
    $('div.checkout a.form_submit').click(function(){
    	if(!$(this).hasClass('loading_gif')){
	    	$(this).html('Processing...');
	    	$('span.loading').show();
	    }else{
	    	return false;
	    }
    });
    
    // Auto-fill pre-existing address
    $('#existing_address').change(function(){
    	
    	if(!$(this).val()){
    	
    		//$('form.address_form input').val('').removeAttr('checked').removeAttr('selected');
    		$('div.address_values').eq(0).children('span').each(function(i){
    			$('form.address_form #' + $(this).attr('class')).val('')
    				.removeAttr('checked').removeAttr('selected').removeAttr('disabled').removeAttr('readonly');
     		});
    	
    	}else{
    		
    		var address_id = $(this).val();
    		$('#address_' + address_id + ' span').each(function(i){
    			// text boxes and selects
    			$('form.address_form #' + $(this).attr('class')).val($(this).html()).attr('readonly','readonly').attr('disabled','disabled');
    			// check boxes
				if($('form.address_form #' + $(this).attr('class')).attr('type')=="checkbox"){
					if($(this).html() =="1"){
						$('form.address_form #' + $(this).attr('class')).attr('checked','checked').attr('disabled','disabled');	
					}
				};
    		});
    	
    		$('#existing_address').val(address_id);
    	};
    	
    	    
    });
	
	// promo form processing
	$('a.add_promo').live('click',function(){
		$(this).before('<div class="promo_inputs"><p class="container"><input type="text" class="textbox" name="promos[]" /><input type="submit" style="width: auto; cursor: pointer;" value="Update" class="button promo_update_button" name="submit" /><span></span></p></div>');
		return false;
	});
	
	// promo form processing
	$('div.promo_inputs input.textbox').live('blur',function(){
		
		var this_box = $(this);
		
		if(!$(this_box).val()) return false;
		
		$.post("/checkout/checkpromo",
			{
				promo_code:$(this_box).val(),
				isajax:1
			},function(msg) {
				var rets = msg.split('_');
				if(rets[0]!='1'){
					$(this_box).parent().children("span").html(rets[1]);
				}else{
					// show delete button
					$(this_box).siblings().eq(0).before('<a href="#" class="promo_delete"><img src="/media/images/delete.png" alt="delete" /></a>').hide();
					$(this_box).parent().children("span").html(rets[1]);
				}
			});
		
		return true;
	});
	$('a.promo_delete').live('click',function(){
		var this_parent = $(this).parent();
		$.post("/checkout/removepromo",
			{
				promo_code:$(this_parent).children("input").val(),
				isajax:1
			},function(msg) {
				$(this_parent).parent().fadeOut();
			});
		return false;
	});
	$('input.promo_update_button').live('click',function(){
		return false;
	});


	$("#form1").submit(function() {
		
		if(	$("#newsletter_email").val().indexOf("@")>-1 && $("#newsletter_email").val().indexOf(".")>-1) {
			$.post("/home/mailinglist",
				{
					newsletter_name:$("#newsletter_name").val(),
					newsletter_email:$("#newsletter_email").val(),
					isajax:1
				},function(msg) {
					if(msg==1) {
						$("#resources .bucket:eq(3)").html("<h6>Thanks!<h6> <p>You've been signed up for our newsletter</p>");
					}
				}
			);
		}
		return false;
	});
	
	// SELECT MENU
	
	/*
	$("select.custom").each(function(i) {
		var z = $("select.custom").length - i; 							
		var width = $(this).width();
		
		var menu = "<ul class='select-menu' style='width: " + (width+50) + "px;' id='path-year'>";
			menu+= "<li style='z-index:" + z + "'><span class='value'>Year</span>";
            menu+= "<ul style='display: none; width:" + (width+23) + "px'>";
			$(this).find("option").each(function() {
				menu+= "<li>" + $(this).text() + "</li>";									 
			});
            menu+= "</ul>";
            menu+= "</li>";
			menu+= "</ul>";
		$(menu).insertAfter(this);
		$(this).hide();
	});
	*/
	
	if($("select#state").length) {
		$("select#state").change(function(){
			var state = $(this).val();
			if(state=="ON" || state=="QC" || state=="NS" || state=="NB" || state=="MB" || state=="BC" || state=="PE" || state=="SK" || state=="AB" || state=="NL"){
				$('select#country').val('CA');
			}else{
				//$('select#country').removeAttr('readonly');
			}
		});
	}
	
	if($("#featuredProducts").length>0) {
		$("#featuredProducts").css({width:$(".featured .bucket").length*170, position:"absolute"});
		$(".featured .right").live("click",function() {
			if($("#featuredProducts:animated").length==0) {
				if($("#featuredProducts").position().left*-1<$("#featuredProducts").width()-170*3) {
					$("#featuredProducts").stop().animate({left:$("#featuredProducts").position().left-170},featuredAnimateComplete)	
				}
			}
		});
		$(".featured .left").live("click",function() {
			if($("#featuredProducts:animated").length==0) {
				if($("#featuredProducts").position().left<0) {
					$("#featuredProducts").stop().animate({left:$("#featuredProducts").position().left+170},featuredAnimateComplete)	
				}
			}
		});	
		function featuredAnimateComplete() {
			$(".featured .left, .featured .right").fadeTo("fast",1);
			var pos = $("#featuredProducts").position().left;
			if(pos>-1) {
				$(".featured .left").fadeTo("fast",.5);		
			}
			if(pos*-1>$("#featuredProducts").width()-170*4) {
				$(".featured .right").fadeTo("fast",.5);						
			}
		}
		featuredAnimateComplete();
	}
	
	$('.select-menu li').hover(function() {
		$(this).find('ul').show();
		$(this).addClass('active');
	}, function() {
		$(this).find('ul').hide();
		$(this).removeClass('active');
	});
	
	
	$('.select-menu').each(function() {
		$(this).find('.value').html($(this).find('ul li:first a').html());
		if($(this).find('ul li:first a').length>0) {
			$(this).data("value",$(this).find('ul li:first a')[0].className.split("_")[1]);
		}
	});
	$('.select-menu li ul li').live("click",function() {
		$parent = $(this).parents('.select-menu:first')
		if($(this).find("a").length>0) {
			$parent.data("value",$(this).find("a")[0].className.split("_")[1])
			$parent.find('.value').text($(this).find("a").text());
			$parent.find("li:first ul").hide();
			$parent.find("li:first").removeClass("active");
		}
	});
	
	
	$("#years").change(function() {
		$.getJSON("/products/selection/eventsbyyear/" + $(this).val(),function(msg) {
			var opts = "";
			for(var o=0;o<msg.length;o++) {
				opts+="<option value='" + msg[o].id + "'>" + msg[o].name + "</value>";
			}
			$("#event").html(opts);
		});
	});
	$("#event_search").live("click",function() {
		var id = $("#event").val();
		var name = $("#event option:selected").text();			
			name = name.replace(/ /g,"-");
			name = name.replace(/\./g,"");	
			name = name.toLowerCase();		
		window.location = "/products/event/" + id + "/" + name;											
	});
	$("#category_search").live("click",function() {
		var id = $("#category").val();
		var name = $("#category option:selected").text();											
			name = name.replace(/ /g,"-");
			name = name.replace(/\./g,"");						
			name = name.toLowerCase();		
		window.location = "/products/category/" + id + "/" +name;
	});
	$("#theme_search").live("click",function() {
		var val = $("#theme").val();
		var name = $("#theme option:selected").attr('lang');													
		window.location = "/products/theme/" + val + "/" + name;
	});	
	
		// Anchor Form Submit
	$('.form_submit').live("click",function(){
		$(this).parents("form").submit();
		return true;
	});	
	
	// Clear Checkout Textboxes
	//$('div.checkout input').clearDefault();
	
	// Copy Shipping Address to Billing Address
	$('#copy_shipping').click(function(){
		
		$('#first_name').val($('#shipping_first_name').val());		
		$('#last_name').val($('#shipping_last_name').val());		
		$('#phone').val($('#shipping_phone').val());		
		$('#business_name').val($('#shipping_business_name').val());		
		$('#street_1').val($('#shipping_street_1').val());		
		$('#street_2').val($('#shipping_street_2').val());		
		$('#city').val($('#shipping_city').val());		
		$('#state').val($('#shipping_state').val());		
		$('#zip_code').val($('#shipping_zip_code').val());		
		$('#country').val($('#shipping_country').val());		
		
	});
	
	
	slides = {
		speed:4000,
		init:function() {
			$(".slides:gt(0)").fadeOut(0);
			$(".media .slides").each(function() {
				$(this).find(".copy p a:first").addClass('button-1');
				$(this).find(".copy p a:last").addClass('button-2');
			});
			$(".controls span").live("click",function() {
				slides.show($(this).index(),this);
				clearInterval(slides.timer);
			});	
			slides.show(0);
			slides.timer = setInterval(slides.loop,slides.speed);		
		},		
		show:function(i) {
			$(".slides").fadeOut();
			$(".slides:eq(" + i + ")").stop().fadeIn();
			$(".controls span.active").removeClass("active");
			$(".controls span:eq(" + i + ")").addClass("active");
			$(".slides:eq(" + i + ")").addClass("active");	
		},
		loop:function() {
			var a = $(".slides.active").index();
			$(".slides.active").removeClass("active");
			a = a < $(".slides").length-1 ? a+1:0;
			slides.show(a);
		}
	}
	slides.init();

	//hide nav in portals
	if((window.location+"").indexOf(".com/portal")>-1) {
		$('.navigation li:not(".last")').remove();	
		$('.navigation ul').prepend('<li class="first"><a>Back to portal</a></li>');
		$('.navigation li.last').css({marginLeft:565});
	}

	if($(".error").length>0) {
		$("html,body").animate({scrollTop:$(".error:first").offset().top});
	}
	
	/*
	* Cancel Order Confirmation 
	*/
	$('a.cancel_order').click(function(){
		var answer = confirm('Are you sure you wish to cancel this order? This action can not be undone.');
		if (!answer) {
			return false;
		}else{
			return true;
		}
	});
	
});
