$(document).ready(function(){
	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);
	
	$.extend({
	  getUrlVars: function(){
	    var vars = [], hash;
	    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	    for(var i = 0; i < hashes.length; i++)
	    {
	      hash = hashes[i].split('=');
	      vars.push(hash[0]);
	      vars[hash[0]] = hash[1];
	    }
	    return vars;
	  },
	  getUrlVar: function(name){
	    return $.getUrlVars()[name];
	  }
	});
	
	// $(".banner.giraffe").click(function(){
	// 	window.location.href='/poster-printing';
	// });
	
	/* Load design banner */
	$('.banner.design-portfolio').each(function() {
	  if($.flash.hasVersion(10)) {
	    $(this).replaceWith($.flash.create({swf: '/flash/banner-design.swf', width: 696, height: 316}));
	  } else {
	    $(this).click(function() {
	      window.location.href='/graphic-design';
	    });
	  }
	});
	
	$("#banner").click(function(){
		window.location.href="/graphic-design/design-portfolio";
	});
	
	$(".banner.design-comp").click(function(){
		window.location.href="/graphic-design/redesign";
	});
	
	$('.banner-collection').cycle({ 
	    fx:     'fade', 
	    timeout: 8500
	});
	
	// $(".banner-container").ready(function(){
		// var banners = new Array();
		// $(".banner").each(function(){	
		// 	banners.push($(this).attr("id"));
		// });
		// $("#" + banners[Math.floor(Math.random() * $(".banner").length)]).removeClass("hidden");
	// });
	
	/* Animate giraffe banner */
/*	$('.banner-container .banner.giraffe').each(function() {
		var $banner = $(this);
		var $pnav = $('.primary-nav').eq(0);
		$pnav.css({position: 'relative'});
		// $banner.show();
		// $banner.find('.giraffe-horns').css({top: 34}).appendTo($pnav);
		
		
		$banner.css({position: 'relative', overflow: 'hidden'});
	
		$banner.find('h2,p').css({position: 'relative', left: -500, opacity: 0.01});
		$banner.find('h1').css({position: 'relative', top: 300, opacity: 0.01});
		$banner.find('a.b-more-information,a.b-request-a-quote').css({position: 'relative', top: 80, opacity: 0.01});
		
		setTimeout(function() {
			$banner.find('h2').animate({left: 0, opacity: 1}, 400, function() {
				setTimeout(function() {
					$banner.find('h1').animate({top: 0, opacity: 1}, 400, function() {
						$banner.find('p').animate({left: 0, opacity: 1}, 625, function() {
							setTimeout(function() {
								$banner.find('a.b-more-information,a.b-request-a-quote').animate({top: 0, opacity: 1}, 300);
							}, 625);
						});
					});
				}, 500);
			});
		}, 1000);
	});*/
	
	$("a.print").click(function(){
		// $('.maincontent').addClass('print');
		window.print();
		return false;
	});
	
	$('a.external').click(function() {
	    window.open($(this).attr('href'));
	    return false;
 	});

	$("a.design-image").colorbox({slideshow:false, height:"650px", width:"900px", opacity:0.40, onOpen: function(){
	}});
		
	$('.date-pick').datePicker({
					createButton:true,
					renderCallback:function($td, thisDate, month, year)
					{
						if (thisDate.isWeekend()) {
							$td.addClass('weekend');
							$td.addClass('disabled');
						}
					}
				}
	).val(new Date().asString()).trigger('change');
	
	$("#state-filter").change(function(){
		window.location = $(this).val();
	});
	
	$(".store-actions a, .other-centres a.request-quote, .other-centres a.upload-file").click(function(){
		var link = $(this);
		$.ajax({
			type: "POST",
			url: "/set_default",
			data: "centre="+$(link).attr("id"),
			success:function(){
				window.location = $(link).attr("href");
			}
		});
		return false;
	});
	
	$("form.sign-up").submit(function(){
		var email = $(".newsletter-subscribe-container #email").val();
		var name = $(".newsletter-subscribe-container #name").val();
		$.ajax({type: "POST",url: "/sign_up",data: "email="+email + "&name="+name, success:function(){
				window.open("/thank-you-for-joining");
				$(".newsletter-subscribe-container #email").val("");
				$(".newsletter-subscribe-container #name").val("");
				
			}
		});
		return false;
	});
	
	$("a.file-delete").live("click", function(){
		var link = $(this);
		$(link).closest(".file-deleting").show();
		
		var IE = /*@cc_on!@*/false;
		if(!($.flash) || !($.flash.available)){
			var filename = decodeURIComponent($(link).attr("href"));
			filename = filename.replace("file:///", "");
			filename = filename.replace(/\//g, "\\");
			$(".filename").val($(".filename").val().replace(filename, ""));
		}else{
			var filename = $(link).attr("href").split("/");
			$(".filename").val($(".filename").val().replace(filename[filename.length-1],""));
		}
		
		
		$(link).closest(".form-row").remove();
		$(".attachment").css({'top': ($(".attachment").css("top").split("px")[0]*1+34)+"px"});
		if($(".file-delete").length == 0){$(".b-send-file").css({"visibility" : "hidden"});}
		return false;
	});
	
    $("a.upload-file").click(function(){
		if($(".selected-filename").val() != ""){
			var file = $("input[name='file']").val();
			if(file==undefined){
				s3_swf1.upload($(".reference_no").val()+"/");
			}else{
				$.ajax({url: '/s3_uploads/generate_s3_signature', dataType: "json", data: "key="+$(".reference_no").val() + "&file="+encodeURIComponent(file) + "&upload_type="+$("input[name=upload_type]").val(), 
					success:function(response){
						$("input[name='Content-Type']").val(response.content_type);
						$("input[name='signature']").val(response.signature);
						$("input[name='redirect']").val(response.redirect);
						$("input[name='policy']").val(response.policy);
						$("input[name='key']").val(response.key);
						if($(".filename").val()==""){
							$("input[name='request[filename]']").val(file);
						}else{
							$("input[name='request[filename]']").val($("input[name='request[filename]']").val() + "," + file);
						}
						$("form.html_upload").submit();
					}
				});
			}
		}
		return false;
	});
	
	$(".html_upload").submit(function(){
		//fix filenames
		var filenames = $(".filename").val().split(",");
		// filenames = filenames.filter(emptyElement);
		var arr = new Array();
		filenames = cleanArray(filenames);
		$(".filename").val(filenames.join(","));
		
		var request = "";
		$(".request-a-quote-popup_submit :input, .html_upload :input, .upload-file-form :input, .request-design :input").each(function(){
			request += $(this).attr("name") + "=" +$(this).val() + "&";
		});
		switch ($("input[name=upload_type]").val()){
			case "quote_request":
				var cookie_name = "request_cookie";
				break;
			case "design_request":
				var cookie_name = "design_cookie";
				break;
			default:
				var cookie_name = "upload_cookie";
		}
		$.cookie(cookie_name, null);
		$.cookie(cookie_name, request, { expires: 1, path: "/" });
	});
	
	function cleanArray(arr){
		var new_arr = new Array();
		$.each(arr, function(index, ele){
			if(ele != ""){
				new_arr.push(ele);
			}
		});
		return new_arr;
	}
	
	function emptyElement(element) {
		if(element == ''){
			return false;
		}else{return true;}
	}
	
	$(".tool-belt a.email, .mini-toolbelt a.email").colorbox({href:".email-to-friend", inline:true, transition:"elastic", height:"350px", width:"650px", open:false,
	 speed:500, opacity:0.40, overlayClose: false, close:"Close", onOpen: function(){
		$("#cboxTitle").remove();
		$(".email-to-friend p.email-page-title").html($(this).attr("title"));
		$("form.email-to-friend-form input[name='url']").val($(this).attr("href"));
		$("form.email-to-friend-form input[name='title']").val($(this).attr("title"));
	}});
	
	$("form.email-to-friend-form").submit(function(){
		var form = $(this);
		var send_ref = true;
		var request = [];
		$(this).find(":input:not(:submit)").each(function(){
			if($(this).val() == ""){
				$(this).closest("li").addClass("invalid");
				send_ref = false;
			}else{
				$(this).closest("li").removeClass("invalid");
				request += "&email_to_friend[" + $(this).attr("name") + "]=" + $(this).val();
			}
		});

		if(send_ref){
			$.ajax({type: "POST", url: "/email_to_friend", data: request, success: function(){
					$(form).find(".input_box").each(function(){
						$(this).val("");
					});
				}
			});
			window.open('/thank-you-for-sharing', '_blank');
			$.fn.colorbox.close();
		}
		return false;
	});

	/*********** deliver franchise pack *******/
	$("form.deliver-franchise-pack").submit(function(){
		var form=$(this);
		var send_pack = true;
		var request = [];
		$(form).find(":input:not(:submit)").each(function(){
			if($(this).is(".required") && $(this).val()==""){
				$(this).closest(".form-row").addClass("invalid");
				send_pack = false;
			}else{
				if($(this).attr("name") == "email"){
					if(!pattern.test($(this).val())){
						$(this).closest(".form-row").addClass("invalid");
						send_pack = false;
					}else{$(this).closest(".form-row").removeClass("invalid");}
				}else{
					$(this).closest(".form-row").removeClass("invalid");
					request += "&request[" + $(this).attr("name") + "]=" + $(this).val();
				}
			}
		});
		
		if(send_pack){
			$.ajax({type: "POST", url: "/deliver_franchise_pack", data: request, success: function(){
					$("form.deliver-franchise-pack :input:not(:hidden,:submit)").each(function(){
						$(this).val("");
					});
					window.open("/thank-you-for-your-enquiry");
					$("p.request-sent").css({visibility: 'visible'});
				}
			});
		}
		return false;	
	});
	/*********** end deliver franchise pack *******/

	/*********** upload file ************/
	$("input[name=subscribe]").click(function(){
		if($(this).is(":checked")){$("input[name=request[subscribe]]").val(1);}
		else{$("input[name=request[subscribe]]").val(0);}
	});
	
	$("form.upload-file-form").submit(function(){
		var form = $(this);
		var send_upload = true;

		$(form).find(".required").each(function(){
			if($(this).val() == ""){
				$(this).closest("div.form-row").addClass("invalid");
				send_upload = false;
			}else{
				if($(this).attr("name") == "request[email]"){
					if(!pattern.test($(this).val())){
						$(this).closest("div.form-row").addClass("invalid");
						send_upload = false;
					}else{$(this).closest("div.form-row").removeClass("invalid");}
				}else if($(this).attr("name") == "request[phone]"){
						if(ValidateForm($(this).val())){
							$(this).closest("div.form-row").removeClass("invalid");
						}else{
							$(this).closest("div.form-row").addClass("invalid");	
							send_upload = false;
						}
				}else{
					$(this).closest("div.form-row").removeClass("invalid");
				}
			}
		});
		
		if(!send_upload || $(".selected-filename").val() != ""){
			return false;
		}else{
			var request = "";
			$(":input.remember-me").each(function(){
				request += $(this).attr("name") + "=" +$(this).val() + "&";
			});
			
			var cookie_name = $("input[name=upload_type]").val() == "quote_request" ? "request_cookie "+$("input[name=request[email]]").val() : "upload_cookie "+$("input[name=request[email]]").val();
			
			$.cookie(cookie_name, request, { path: "/" });
		}
	});
	/*********** end upload file ************/
	
	/*************** request for quotes *************/
	$("li > a.product-quote").click(function(){
		li = $(this).closest('li');
		if($(li).is(".up")){li.show().removeClass("up").addClass("down").animate({height:315}, 500);}
		else{li.hide().addClass("up").animate({height: 79},500, function(){$(this).removeClass("down");});}
		return false;
	});
	
	// funky-nav small form submit action
	$(".request-a-quote-form").submit(function(){
	 	var form = $(this);
		var request = [];
		$(form).find(":input:not(:submit)").each(function(){
			request += "&request[" + $(this).attr("name") + "]=" + encodeURIComponent($(this).val());
		});
		window.location = $(form).attr("action") + "?" + request;
		return false;
	});
	
	$(".request-a-quote-popup_submit").submit(function(){
		var form = $(this);
		var send_request = true;

		$(form).find(".required").each(function(){
			if($(this).val()==""){
				$(this).closest("div.form-row").addClass("invalid");
				send_request = false;
			}else{
				if($(this).attr("name") == "request[email]"){
					if(!pattern.test($(this).val())){
						$(this).closest("div.form-row").addClass("invalid");
						send_request = false;
					}else{$(this).closest("div.form-row").removeClass("invalid");}
				}else if($(this).attr("id") == "request-phone"){
					if(ValidateForm($(this).val())){
						$(this).closest("div.form-row").removeClass("invalid");
					}else{
						$(this).closest("div.form-row").addClass("invalid");	
						send_request = false;
					}
				}else{$(this).closest("div.form-row").removeClass("invalid");}
			}
		});
		
		if(!send_request || $(".selected-filename").val() != ""){
			return false;
		}else{
			var request = "";
			$(":input.remember-me").each(function(){
				request += $(this).attr("name") + "=" +$(this).val() + "&";
			});
			
			var cookie_name = $("input[name=upload_type]").val() == "quote_request" ? "request_cookie "+$("input[name=request[email]]").val() : "upload_cookie "+$("input[name=request[email]]").val();
			
			$.cookie(cookie_name, request, { path: "/" });
		}
	});
	
	$("form.request-a-quote-popup_submit #request-email, form.upload-file-form #email").one("blur", function(){
		var cookie_type = $("input[name=upload_type]").val() == "quote_request" ? "request_cookie ": "upload_cookie ";
		if($("input[name=request[email]]").val() && $.cookie(cookie_type + $("input[name=request[email]]").val())){
			var remembered = $.cookie(cookie_type + $("input[name=request[email]]").val());
			$.each(remembered.split("&"), function(index, value){
				var p = value.split("=");
				$(":input[name="+ p[0] + "]").val(p[1]);
			});
		}
	});
	/************** end request for quotes **************/
	
	/*************** begin request designs *************/
	
	$(".request-design").submit(function(){
		var form = $(this);
		var send_request = true;

		$(form).find(".required").each(function(){
			if($(this).val()==""){
				$(this).closest("div.form-row").addClass("invalid");
				send_request = false;
			}else{
				if($(this).attr("name") == "request[email]"){
					if(!pattern.test($(this).val())){
						$(this).closest("div.form-row").addClass("invalid");
						send_request = false;
					}else{$(this).closest("div.form-row").removeClass("invalid");}
				}else if($(this).attr("id") == "request-phone"){
					if(ValidateForm($(this).val())){
						$(this).closest("div.form-row").removeClass("invalid");
					}else{
						$(this).closest("div.form-row").addClass("invalid");	
						send_request = false;
					}
				}else{$(this).closest("div.form-row").removeClass("invalid");}
			}
		});

		if(!send_request || $(".selected-filename").val() != ""){
			return false;
		}else{
			var request = "";
			$(":input.remember-me").each(function(){
				request += $(this).attr("name") + "=" +$(this).val() + "&";
			});
			
			var cookie_name = "design_cookie "+$("input[name=request[email]]").val();
			
			$.cookie(cookie_name, request, { path: "/" });
		}
	});
	
	/************** end request ********************/

	/*********** portfolio **************/
   	$("a.product-thumb").colorbox({opacity:0.40, height:"500px", width:"500px"});
	$("a.product-coverflow").click(function(){
		if($(this).css("opacity")==1){$.fn.colorbox({href:$(this).attr("href"), opacity:0.40, height:"500px", width:"500px", open:true});}
		else{$("#coverflow-product-name").html($(this).find("img").attr("alt"));}
		return false;
	});
	
	$(".btn-thumbnail").click(function(){ $(".portfolio-grid").css({visibility: 'visible'}); $(".portfolio-coverflow").css({visibility: 'hidden'}); });
	$(".btn-coverflow").click(function(){ $(".portfolio-grid").css({visibility: 'hidden'}); $(".portfolio-coverflow").css({visibility: 'visible'}); });
	
	$("#coverflow").coverflow({
		select: function(event, sky) {
			$('#slider').slider('value', sky.value+1);
		}
	});
	$("#slider").slider({
		min: 1,
		max: $('#coverflow > *').length,
		slide: function(event, ui) {
			// Call the select method in the coverflow, since it's zero-based we need to substract 1
			// Note: Third argument is set to true because we don't want to fire the callback (no race cond.)
			$('#coverflow').coverflow('select', ui.value-1, true);
		}
	});
	$('#slider').bind('slidestop', function(event, ui) {
		var index = $(this).slider('option', 'value');
		$("#coverflow-product-name").html($("#coverflow").find("img").eq(index-1).attr("alt"));
	});
	$('product-coverflow').click(function(){ return false; });
	
	// Tabs
    $("div.portfolio-tab-container").each(function() {
      var tabContainers = $(this).children('div');
      if(tabContainers.length > 1) {
        tabContainers.hide().eq(1).show();
        $(this).find('ul.tab-nav a').click(function() {
          tabContainers.hide().filter(this.hash).show();
          $(this).closest('ul.tab-nav').find('a').removeClass('selected');
          $(this).addClass('selected');
          return false;
        }).eq(1).click();
      }
    });
	/**************** end portfolio *****************/
	
	/*********** CARDS ************/

	$.each($(".content-slider"), function(index, value){
		var slider = $(this).attr("id");
		$("#"+slider).slider({
			animate: true,
			min: 0,
			max: $("."+slider +" .content-card").length,
			change: function handleSliderChange(event, ui){
			  var maxScroll = $("."+slider).attr("scrollWidth") - $("."+slider).width();
			  $("."+slider).animate({scrollLeft: ui.value * (maxScroll / 100) }, 1000);
			},
			slide: function handleSliderSlide(event, ui){
			  var maxScroll = $("."+slider).attr("scrollWidth") - $("."+slider).width(); 
		      $("."+slider).attr({scrollLeft: ui.value * (maxScroll / 100) });
			}
		});
	});
	
	function generate_thumbnail(image, w, h){
		if(image == null){
			return "";
		}else{
			var split_image = image.split(".");
			var ext = split_image[split_image.length-1];
			split_image[split_image.length-1] = "thumbnail."+ h + "x" + w + "t";
			split_image.push(ext);
			return split_image.join(".");
		}
	}
	
	$("a.card-show").click(function(){
		var link = $(this);
		$(".message-selection option").removeClass("withPic"); 
		$.getJSON($(link).attr("href"),function(response){
			var height = response.card.landscape == true ? 180 : 280;
			$(".card-front").html("<img src='" + generate_thumbnail(response.card.front, 240, height) + "' width='240' height='"+height+"' />");
			var back = generate_thumbnail(response.card.back, 240, height);
			$(".card-back").html("<img src='" + back + "' width='240' height='"+height+"' />");
			$(".card-name").html(response.card.event + " - " + response.card.name);
			$(".card-code").html(response.card.code);
			$(".card-sizes").html(response.card.sizes);
			var messages = response.card.messages;
			$.each(messages, function(index, value){
				$('select#card_messages option[value="'+value[0]+'"]').addClass("withPic");
				$('select#card_messages option[value="'+value[0]+'"]').attr("rel", value[1]);
			});
			$('select#card_messages option:first').addClass("withPic");
			$('select#card_messages option:first').attr("rel", back);
			$("#card_messages").val("");
			$("#card_quantity").val("20");
			$(".cards-add").attr("rel", response.card.id);
			$.fn.colorbox({'href':'.card-popup', transition:'elastic', speed:500, open:true, inline:true, height:"750px", width:"750px", opacity:0.40, onOpen: function(){
				
			}});
		});
		return false;
	});
	
	$(".message-selection").change(function(){
		var opt = $(this).find("option:selected");
		if($(opt).attr("class") == "withPic"){
			$("p.card-back img").attr("src", generate_thumbnail($(opt).attr("rel"), 240, 180));
		}else{
			$("p.card-back img").attr("src", "/uploads/cards/photo_not_available.jpg");
		}
	});
	
	$(".card-buttons > .cards-continue").click(function(){$.fn.colorbox.close();return false;});
	$(".cards-add").click(function(){
		var card_quan = $("#card_quantity").val();
		if(card_quan != ""){
			var cookie_name = "card_cart";
			var card_id = $(".cards-add").attr("rel");
			var card_msg = $(".message-selection").val();
			if($.cookie(cookie_name) == null){
				//no cookie, create and add card ID + Quantity to cookie
				var cards = new Array();
				cards.push(card_id+":"+card_quan+":"+card_msg);
				$.cookie(cookie_name, cards, {expires:7, path: "/"});
			}else{
				//existing cookie, find if selection exist, add to it
				cards = $.cookie(cookie_name).split(",");
				cards.push(card_id+":"+card_quan+":"+card_msg);
				$.cookie(cookie_name, null);
				$.cookie(cookie_name, cards, {expires:7, path:"/"});
			}
			// $.fn.colorbox.close();return false;	
		}
		// return false;
	});
	
	
	$("a.update-cart").click(function(){
		update_cart();
		location.reload(true);
		return false;
	});
	
	function update_cart(){
		var cookie_name = "card_cart";
		var cards = new Array();
		$.each($(".card-delete"), function(index, value){
			if($(this).is(":not(:checked)") && $(this).prev(".quantity").val() != 0 && $(this).prev(".quantity").val() != ""){
				cards.push($(this).attr("id").split("-")[1] + ":" + $(this).prev(".quantity").val() + ":" + $(this).siblings(".card-msg-id").val());
			}
		});
		$.cookie(cookie_name, null);
		$.cookie(cookie_name, cards, {expires:7, path:"/"});
	}
	
	$("a.link-card-delete").click(function(){
		$(this).parent().fadeOut("slow");
		$("#"+$(this).attr("rel")).attr("checked", true);
		update_cart();
		return false;
	});
	
	$(".card-request-a-quote").submit(function(){
		var form = $(this);
		var send_request = true;

		$(form).find(".required").each(function(){
			if($(this).val()==""){
				$(this).closest("div.form-row").addClass("invalid");
				send_request = false;
			}else{
				if($(this).attr("name") == "request[email]"){
					if(!pattern.test($(this).val())){
						$(this).closest("div.form-row").addClass("invalid");
						send_request = false;
					}else{$(this).closest("div.form-row").removeClass("invalid");}
				}else if($(this).attr("id") == "request-phone"){
					if(ValidateForm($(this).val())){
						$(this).closest("div.form-row").removeClass("invalid");
					}else{
						$(this).closest("div.form-row").addClass("invalid");	
						send_request = false;
					}
				}else{$(this).closest("div.form-row").removeClass("invalid");}
			}
		});
		
		if(!send_request){
			return false;
		}else{
			update_cart();
			// var request = "";
			// 			$(":input.remember-me").each(function(){
			// 				request += $(this).attr("name") + "=" +$(this).val() + "&";
			// 			});
			// 			var cookie_name = "card_request_cookie";
			// 			
			// 			$.cookie(cookie_name, request, { path: "/" });
			
			//////////////////////
			// var file = $("input[name='file']").val();
			// if(file==undefined){
			// 	s3_swf1.upload($(".reference_no").val()+"/");
			// }else{
			// 	$.ajax({url: '/s3_uploads/generate_s3_signature', dataType: "json", data: "key="+$(".reference_no").val() + "&file="+encodeURIComponent(file) + "&upload_type="+$("input[name=upload_type]").val(), 
			// 		success:function(response){
			// 			$("input[name='Content-Type']").val(response.content_type);
			// 			$("input[name='signature']").val(response.signature);
			// 			$("input[name='redirect']").val(response.redirect);
			// 			$("input[name='policy']").val(response.policy);
			// 			$("input[name='key']").val(response.key);
			// 			if($(".filename").val()==""){
			// 				$("input[name='request[filename]']").val(file);
			// 			}else{
			// 				$("input[name='request[filename]']").val($("input[name='request[filename]']").val() + "," + file);
			// 			}
			// 			$("form.html_upload").submit();
			// 		}
			// 	});
			// }
			///////////////
		}
	});
	
	/********* END CARDS ************/
	
	/*************** DESIGN COMP FORM ****************/
	$("input[name=subscribe]").click(function(){
		if($(this).is(":checked")){$("input[name=competition_entry[subscribe]]").val(1);}
		else{$("input[name=competition_entry[subscribe]]").val(0);}
	});
	
	$("input[name=terms]").click(function(){
		if($(this).is(":checked")){$("input[name=competition_entry[terms]]").val(1);}
		else{$("input[name=competition_entry[terms]]").val("");}
	});
	
	$("form.design-comp-form").submit(function(){
		var form = $(this);
		var send_form = true;
		$(form).find(".required").each(function(){
			if($(this).val() == ""){
				$(this).closest("div.form-row").addClass("invalid");
				send_form = false;
			}else{
				if($(this).attr("name") == "competition_entry[email]" || $(this).attr("name") == "competition_entry[business_email]"){
					if(!pattern.test($(this).val())){
						$(this).closest("div.form-row").addClass("invalid");
						send_form = false;
					}else{$(this).closest("div.form-row").removeClass("invalid");}
				}else if($(this).attr("name") == "competition_entry[answer]"){
					var words = $("form.design-comp-form textarea[name=competition_entry[answer]]").val();
					if(word_count(words, this) > 100 || words == ""){
						$(this).closest("div.form-row").addClass("invalid");
						$(".warning").css({"visibility": "visible"});
						send_form = false;
					}else{$(this).closest("div.form-row").removeClass("invalid");$(".warning").css({"visibility": "hidden"});}
				}else{
					$(this).closest("div.form-row").removeClass("invalid");
				}
			}
		});
		if(!send_form || $("input[name=competition_entry[terms]]").val() != "1"){return false;}
	});
	
	function word_count(words,x){
		var y=words;
		var r = 0;
		a=y.replace(/\s/g,' ');
		a=a.split(' ');
		for (z=0; z<a.length; z++) {if (a[z].length > 0) r++;}
		return r;
	}
	
	
	$("a.pop-window").click(function() {
		window.open($(this).attr('href'),'mywin','left=20,top=20,width=1000,height=1000,toolbar=1,scrollbars=1,resizable=0');
		return false;	
	});
	/*************** END DESIGN COMP FORM ************/
	
	/************* SAMPLE **************/
	$(".b-free-sample-pack.colorbox").colorbox({href:".free-sample", transition:"elastic", height:"500px", width:"850px", open:false,
	 speed:500, inline:true, opacity:0.40, overlayClose: false, close:"Close"});
	$("form.sample-pack-form").submit(function(){
		var form = $(this);
		var send_pack = true;
		var request = [];

		$(form).find(":input:not(:submit, :checkbox)").each(function(){
			if($(this).val()==""){
				$(this).closest("li").addClass("invalid");
				send_pack = false;
			}else{
				if($(this).attr("name") == "email"){
					if(!pattern.test($(this).val())){
						$(this).closest("li").addClass("invalid");
						send_pack = false;
					}else{$(this).closest("li").removeClass("invalid");}
				}else{
					$(this).closest("li").removeClass("invalid");
					request += "&request[" + $(this).attr("name") + "]=" + $(this).val();
				}
			}
		});
		
		if(send_pack){
			var subscribe = $(form).find(":input[name=subscribe]");
			request += "&request[subscribe]="+$(subscribe).is(":checked");
			
			$.ajax({type: "POST", url: "/receive_sample_pack", data: request, success: function(){
					window.open("/uploads/sample-pack-stuff/sample-pack.pdf");
					$("form.sample-pack-form :input:not(:hidden, .send-sample-pack)").each(function(){
						$(this).val("");
					});
					$(subscribe).attr("checked", false);
					$.fn.colorbox.close();
				}
			});
		}
		return false;
	});
	/*********** end free sample box *************/
	
	$("form.comment_box").submit(function(){
		var form = $(this);
		var send_comment = true;
		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);
		var request=[];
	 	$(form).find(":input:not(:submit, .unrequired)").each(function(){
			if($(this).val()==""){
				$(this).closest(".form-row").addClass("invalid");
				send_comment = false;
			}else{
				if($(this).attr("name") == "page_comment[email]"){
					if(!pattern.test($(this).val())){
						$(this).closest(".form-row").addClass("invalid");
						send_comment = false;
					}else{$(this).closest(".form-row").removeClass("invalid");}
				}else{
					$(this).closest(".form-row").removeClass("invalid");
					request += "&" + $(this).attr("name") + "]=" + $(this).val();
				}
			}
		});
		
		if(send_comment){			
			var page = $(form).attr("action").split("/");
			request += "&page=" + page[page.length-1];
			$.ajax({type: "POST", url: "/admin/comments", data: request, success: function(){
					$(form).find(".comment_fail").closest('li').hide();
					$("form.comment_box :input:not(:hidden, .post_comment)").each(function(){
						$(this).val("");
					});
					$(form).find(".comment_success").closest('li').show();
				}
			});
		}
		return false;
	});
	
    $("form.request-simple-quote").submit(function(){
		var type = $(this).find(":input[name='product-type']");
		var description = $(this).find(":input[name='description']");
		var email = $(this).find("input[name='email']");
		
		$.ajax({type: "POST", url: "/request_quote", data: "request[type]=" + $(type).val() + "&request[description]=" + $(description).val() + "&request[email]=" + $(email).val(),
			success: function(){
				$(description).val('');
				$(email).val('');
			}
		});
		return false;
	});
	
	$("form.download-franchise-pack").submit(function(){
		var send_form = true;
	 	$(this).find(":input:not(:submit)").each(function(){
			if($(this).val()==""){
				$(this).closest(".form-row").addClass("invalid");
				send_form = false;
			}else{
				if($(this).attr("name") == "franchise[email]"){
					if(!pattern.test($(this).val())){
						$(this).closest(".form-row").addClass("invalid");
						send_form = false;
					}else{$(this).closest(".form-row").removeClass("invalid");}
				}else{$(this).closest(".form-row").removeClass("invalid");}
			}
		});
		if(!send_form){return false;}
	});
	
	$('.btn-share-article').click(function() {
		var sharethis = $(this).next('.share-article');
		sharethis.stop(true);
		if (sharethis.is(".down")) {
			$(this).removeClass("look-at-me");
			sharethis.removeClass("down").animate({
					height: 0
			},
			40);
		} else {
			$(this).addClass("look-at-me");
			sharethis.show().addClass("down").animate({
					height: 228
			},
			200);
		}
		return false;
	});
	
	// Home page content sliders
	$('.print-solutions-container, .print-portfolio-container').each(function() {
		var $container = $(this);
		var $contentItems = $container.find('.content-item').remove();
		$container.append('<div class="content-scroll"><div class="content-holder"></div></div><div class="content-slider"><div class="content-slider-holder"><div class="content-slider-items"><div class="content-slider-selection"></div></div></div></div>');
		var $contentHolder = $container.find('.content-holder');
		$contentHolder.append($contentItems);
		var contentWidth = $contentItems.eq(1).position().left;
		var $slider = $container.find('.content-slider');
		var $sliderItems = $slider.find('.content-slider-items');
		var sliderItemsWidth = 5;
		$container.find('.content-item > :heading:first-child').each(function() {
			var $link = $('<a href="#">' + $(this).text() + '</a>').appendTo($sliderItems);
			sliderItemsWidth += ($link.width() + 15);
		});
		var $selection = $sliderItems.find('.content-slider-selection');
		$slider.find('.content-slider-items a').bind('select', function(e, options) {
			var $item = $(this);
			var index = $item.prevAll('a').length;
			var left = $item.position().left;
			var scroll = Math.min(Math.max(-left + ($slider.width() / 3.5), -(sliderItemsWidth - $slider.width()) - 5), 0) + 5;
			$item.siblings().removeClass('selected');
			if(options && options.animate) {
				$sliderItems.stop().animate({left: scroll});
				$contentHolder.stop().animate({left: -index * contentWidth});
				$selection.stop().animate({left: left, width: $item.width() + 15}, function() {
					$item.siblings().removeClass('selected');
					$item.addClass('selected');
				});
			} else {
				$sliderItems.css({left: scroll});
				$contentHolder.css({left: -index * contentWidth});
				$selection.css({left: left, width: $item.width() + 15});
				$item.addClass('selected');
			}
		}).click(function() {
			$(this).trigger('select', {animate: true});
			return false;
		}).eq(0).trigger('select');
	});
	
	// Store details
	$('.header a.local-store').click(function() {
		var $popup = $(this).next('.store-details-popup');
		if($popup.is(':hidden')) {
			$popup.stop().fadeIn('fast');
		} else {
			$popup.stop().fadeOut('fast');
		}
		return false;
	});
	
	// Store details popup close button
	$('.header .store-details-popup a.store-details-close').click(function() {
		$(this).closest('.store-details-popup').stop().fadeOut('fast');
		return false;
	});
	
	// Sets selected centre as default
	$(".select-current-centre a.set-as-default").live("click", function(){
		var link = $(this);
		var centre = $(link).attr("name");
		$.ajax({type: "POST", url: "/set_default",
				data: "centre=" + centre,
				success: function(){
 					 $(link).replaceWith("<p class='detail'>Default Centre</p>");
				}
		});
		return false;
	});
	
	// Large google map for browse centres
	if(typeof(google) != 'undefined' && typeof(google.maps) != 'undefined' && $('.large-map').length > 0) {
		function infoWindowContent(centre) {
			var html = '<div class="map-info-window-content" style="width: 320px;"><h5><a href='+ centre.path +'>Kwik Kopy ' + centre.name + '</a></h5>';
			html += '<h6>Address</h6>';
			html += '<p class="address_lines">' + centre.address_lines.join('<br />') + '</p>';
			html += '<h6>Contact</h6>';
			html += '<p>Ph: ' + centre.phone + '</p>';
			html += '<p>Email: ' + centre.email + '</p>';
			html += '<p class="select-current-centre"><a class="set-as-default" name="'+ centre.centre_url +'" href="/set_default">Set as default Kwik Kopy Centre</a></p>';
			html += '<p class="more-info"><a href="' + centre.path + '">More info...</a></p>';
			if(centre.has_image){
				html += '<span class="centre-image""><a href='+ centre.path +'><img src="'+ centre.image_location +'" alt="'+ centre.name +'" width="130" height="130"/></a></span>';
			}else{
				html += '<span class="centre-image""><a href='+ centre.path +'><img src="/uploads/centre-images/DEFAULT_IMAGE.jpg" alt="'+ centre.name +'" width="130" height="130"/></a></span>';
			}
			html += '</div>';
			return $(html).get(0);
		}
		
		$.ajax({
			url: '/browse-centres/map-info.json',
			type: 'GET',
			dataType: 'json',
			success: function(centres) {
				var $mapContainer = $('.large-map:first');
				var mapContainer = $mapContainer.get(0);
				var gMap = new google.maps.Map(mapContainer, {
					zoom: 4,
					center: new google.maps.LatLng(-25.274398, 133.775136),
					mapTypeId: google.maps.MapTypeId.ROADMAP
				});
				
				mapContainer.map = gMap;
				mapContainer.infoWindows = {};
				var gOpenInfoWindows = [];
				
				$mapContainer.bind('openInfoWindow', function(e, centrePath) {
					var gInfoWindow = mapContainer.infoWindows[centrePath];
					if(gInfoWindow) {
						$.each(gOpenInfoWindows, function() { this.close(); });
						gOpenInfoWindows = [gInfoWindow];
						gInfoWindow.open(gMap, gInfoWindow.relatedMarker);
					}
				}).bind('goToBounds', function(e, bounds) {
					var gBounds = new google.maps.LatLngBounds(
						new google.maps.LatLng(bounds.southwest.latitude, bounds.southwest.longitude),
						new google.maps.LatLng(bounds.northeast.latitude, bounds.northeast.longitude)
					);

					// var gRectOpts = {
					// 	bounds: gBounds,
					// 	clickable: false,
					// 	fillColor: "#FF0000",
					// 	fillOpacity: 0.2,
					// 	map: gMap
					// };
					// 
					// var gRect = new google.maps.Rectangle(gRectOpts);

					gMap.fitBounds(gBounds);
				}).bind('resizeMap', function() {
					google.maps.event.trigger(gMap, 'resize');
				});
				
				$.each(centres, function() {
					var gMarker = new google.maps.Marker({
						map: gMap,
						position: new google.maps.LatLng(this.centre.latitude, this.centre.longitude),
						title: 'Kwik Kopy ' + this.centre.name,
						icon: '/images/map-marker.gif',
						clickable: true
					});
					
					var gInfoWindow = new google.maps.InfoWindow({
						content: infoWindowContent(this.centre)
					});
					gInfoWindow.relatedMarker = gMarker;
					mapContainer.infoWindows[this.centre.path] = gInfoWindow;
					
					google.maps.event.addListener(gMarker, 'click', function() {
						$.each(gOpenInfoWindows, function() { this.close(); });
						gOpenInfoWindows = [gInfoWindow];
						gInfoWindow.open(gMap, gMarker);
					});
					
				});
			}
		});
		
		$('#postcode-filter').attr('autocomplete', 'off').focus(function() {
			$(this).select();
		}).keydown(function(event) {
			switch(event.which) {
			case 38: /* up arrow */
				$(this).trigger('selectmove', 'up');
				return false;
			case 40: /* down arrow */
				$(this).trigger('selectmove', 'down');
				return false;
			case 9:  /* tab */
				$selected = $('.search-postcode ul li a.selected:first');
				if($selected.length > 0) {
					$selected.trigger('click');
					return true;
				}
			case 13: /* enter */
				$selected = $('.search-postcode ul li a.selected:first');
				if($selected.length > 0) {
					$selected.trigger('click');
					$(this).blur();
					$('.search-postcode ul').hide();
				}
				return false;
			}
			return true;
		}).bind('selectmove', function(event, direction) {
			var $ul = $('.search-postcode ul');
			if($ul.length == 0) return;
			var $selected = $ul.find('li a.selected:first');
			var $nextSelected;
			if(direction == 'up') {
				if($selected.length == 0) {
					$nextSelected = $ul.find('li:last-child a');
				} else {
					$nextSelected = $selected.closest('li').prev().find('a');
				}
			} else if(direction == 'down') {
				if($selected.length == 0) {
					$nextSelected = $ul.find('li:first-child a');
				} else {
					$nextSelected = $selected.closest('li').next().find('a');
				}
			}
			if($nextSelected && $nextSelected.length > 0) {
				$selected.removeClass('selected');
				$nextSelected.addClass('selected');
			}
		}).delayedObserver(function() {
			$('.search-results-loading').show();
			$.ajax({
				url: '/places.json?query=' + $(this).val(),
				type: 'GET',
				dataType: 'json',
				success: function(data) {
					$('.search-results-loading').hide();
					$('.search-postcode ul').remove();
					$ul = $('<ul>').appendTo($('.search-postcode'));
					if(data.length == 0) $ul.append('<li class="error">No matching postcodes or suburbs</li>');
					$.each(data, function(i) {
						var place = this.place;
						var $li = $('<li>').appendTo($ul);
						var $link = $('<a href="#">' + place.name + '</a>').appendTo($li);
						if(i == 0) $link.addClass('selected');
						$link.click(function() {
							$('#postcode-filter').val(place.name);
							var $map = $('.large-map:first');
							var $mapdetails = $(".map-details");
							$map.css({"width" : "75%", "float" : "right"}).trigger('resizeMap');
							/*$mapdetails.replaceWith("<div class='map-details'><h4>Kwik Kopy Centre/s that service this area:<br /> "+ $link.html() +"</h4><ul></ul></div>");
							if(place.catered_centres.length < 1){
								$(".map-details ul").append("<li><p>Please refer to the map for your closest centre</p></li>");
							}else{
								$.each(place.catered_centres,function(x){
									var centre = this.centre;
									$(".map-details ul").append("<li><strong><a class='centre-link' href='/browse-centres/"+ centre.centre_url +"'>Kwik Kopy "+centre.name +"</a></strong><p>Ph: " + centre.phone + "</p></li>");
								});
							}
							*/
							 $mapdetails.replaceWith("<div class='map-details'><h4>Kwik Kopy Centre/s that service this area:<br /> "+ $link.html() +"</h4><ul></ul></div>");
							                             if(place.nearest_centres.length < 1){
							 	$(".map-details ul").append("<li><p>Please refer to the map for your closest centre</p></li>");
							 }else{
							 	$.each(place.nearest_centres,function(x){
							 		var centre = this.centre;
						 		$(".map-details ul").append("<li><a class='centre-link' href='/browse-centres/"+ centre.centre_url +"'>"+centre.name+ ", " + centre.postcode +"</a></li>");
						 	});
							 }
						
						
							
							$(".map-details").css({"display" : "block"});
							$map.trigger('goToBounds', place.box_with_nearest_centre);
							if(place.nearest_centre) {
								$map.trigger('openInfoWindow', place.nearest_centre.centre.path);
							}
							$ul.hide();
							return false;
						}).mouseenter(function() {
							$(this).addClass('selected');
						}).mouseleave(function() {
							$(this).removeClass('selected');
						});
					});
				},
				error: function() {
					$('.search-results-loading').hide();
					$('.search-postcode ul').remove();
					$('.search-postcode').append('<ul><li class="error">Error: Search results not available</li></ul>');
				}
			});
		});
	}
	
  // Animate Sharkey Media logo
  $('a.sharkey-out').css({opacity: 0});
    $('a.sharkey').click(function(event){event.preventDefault();});
    $('a.sharkey').mouseenter(function() {
      $('a.sharkey').addClass("sharkey-on");
      $('a.sharkey-out').show().animate({width: 250, opacity: 1}, 300);
    });
    $('a.sharkey').mouseleave(function() {
      $('a.sharkey-out').fadeTo(4000, 1, function() {
        $(this).animate({width: 0, opacity: 0}, 400, function() {
          $(this).hide();
          $('a.sharkey').removeClass("sharkey-on");
        });
      });
    });

	/* share links config */
	$("a.print").click(function(){
		// $('.maincontent').addClass('print');
		// 	window.print();
		// 	return false;
	});
	
	$("li a.delic").click(function(){
		var url = $(this).attr("href");
		var title = $(this).attr("title");
		window.open('http://delicious.com/save?v=5&noui&jump=close&url='+encodeURIComponent(url)+'&title='+encodeURIComponent(title), 'delicious','toolbar=no,width=550,height=550'); 
		return false;
	});
	
	$("li a.facebook").click(function(){
		var url = $(this).attr("href");
		var title = $(this).attr("title");
		window.open("http://www.facebook.com/sharer.php?u="+encodeURIComponent(url)+"&t="+encodeURIComponent(title));
		return false;
	});
	
	$("li a.twitter").click(function(){
		var url = $(this).attr("href");
		var title = $(this).attr("title");
		window.open("http://twitter.com/home?status=Currently%20reading%20"+encodeURIComponent(url));
		return false;
	});
	
	$("li a.myspace").click(function(){
		var url = $(this).attr("href");
		var title = $(this).attr("title");
		window.open("http://www.myspace.com/index.cfm?fuseaction=postto&t="+encodeURIComponent(title)+"&u="+encodeURIComponent(url));
		return false;
	});
	
	$("li a.google").click(function(){
		var url = $(this).attr("href");
		var title = $(this).attr("title");
		window.open("http://www.google.com/bookmarks/mark?op=edit&output=popup&bkmk="+encodeURIComponent(url)+"&title="+encodeURIComponent(title), "bkmk_popup");
		return false;
	});
	
	$("li a.digg").click(function(){
		var url = $(this).attr("href");
		var title = $(this).attr("title");
		window.open("http://digg.com/submit?phase=2&url="+encodeURIComponent(url)+"&title="+encodeURIComponent(title));
		return false;
	});
	
	$("li a.buzz").click(function(){
		var url = $(this).attr("href");
		var title = $(this).attr("title");
		window.open("http://buzz.yahoo.com/buzz?targetUrl="+encodeURIComponent(url));
		return false;
	});
	
	$("li a.live").click(function(){
		var url = $(this).attr("href");
		var title = $(this).attr("title");
		window.open("https://skydrive.live.com/sharefavorite.aspx%2f.SharedFavorites?mkt=en-us&url="+ encodeURIComponent(url) +"&title="+ encodeURIComponent(title));
		return false;
	});
	
	/**
	 * DHTML phone number validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
	 */

	var digits = "0123456789";
	var phoneNumberDelimiters = "()- ";
	var validWorldPhoneChars = phoneNumberDelimiters + "+";
	var minDigitsInIPhoneNumber = 8;

	function isInteger(s)
	{   var i;
	    for (i = 0; i < s.length; i++)
	    {   
	        var c = s.charAt(i);
	        if (((c < "0") || (c > "9"))) return false;
	    }
	    return true;
	}
	function trim(s)
	{   var i;
	    var returnString = "";

	    for (i = 0; i < s.length; i++)
	    {   
	        var c = s.charAt(i);
	        if (c != " ") returnString += c;
	    }
	    return returnString;
	}
	function stripCharsInBag(s, bag)
	{   var i;
	    var returnString = "";
	    for (i = 0; i < s.length; i++)
	    {
	        var c = s.charAt(i);
	        if (bag.indexOf(c) == -1) returnString += c;
	    }
	    return returnString;
	}

	function checkInternationalPhone(strPhone){
	var bracket=3;
	strPhone=trim(strPhone);
	if(strPhone.indexOf("+")>1) return false;
	if(strPhone.indexOf("-")!=-1)bracket=bracket+1;
	if(strPhone.indexOf("(")!=-1 && strPhone.indexOf("(")>bracket)return false;
	var brchr=strPhone.indexOf("(");
	if(strPhone.indexOf("(")!=-1 && strPhone.charAt(brchr+3)!=")")return false;
	if(strPhone.indexOf("(")==-1 && strPhone.indexOf(")")!=-1)return false;
	s=stripCharsInBag(strPhone,validWorldPhoneChars);
	return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
	}

	function ValidateForm(number){
		if (checkInternationalPhone(number)==false){
			return false;
		}
		return true;
	 }
});

/* delayedObserver from http://code.google.com/p/jquery-utils/ */
$.extend($.fn, {
  delayedObserver: function(callback, delay, options) {
    return this.each(function() {
      var el = $(this);
      var op = options || {};
      el.data('oldval', el.val())
        .data('delay', delay || 0.5)
        .data('condition', op.condition || function() { return ($(this).data('oldval') == $(this).val()); })
        .data('callback', callback)
        [(op.event||'keyup')](function() {
          if (el.data('condition').apply(el)) { return; }
          else {
            if (el.data('timer')) { clearTimeout(el.data('timer')); }
            el.data('timer', setTimeout(function() {
              el.data('callback').apply(el);
            }, el.data('delay') * 1000));
            el.data('oldval', el.val());
          }
        });
    });
  }
});
