var cf_interval = 5000;
var selected = 0;
var flip;
var disabled = Array();

$(document).ready(function(){
	
	$("#navbar ul").superfish({
		pathClass: 'current' 
	});
	
	$("#mailing_list input").hint();
	
	initMailingList();
	initProductPage();
	initPayPal();
	initScatters();
	
});

function startCrossFade(){
	flip = setInterval("crossfade()", cf_interval);
}

function crossfade(){

	selected++;
	if(selected >= $("#carousel .carousel_slide_indicator").length){
		selected = 0;
	}

	$("#carousel .carousel_slide_indicator:eq(" + selected + ")").trigger("mouseenter");
	
}


function initScatters(){
	$("#scatter").reorder()
	var images = $("#scatter img");
	$(images).css('opacity', '0');
	
	
	$(images).each(function(i, elem){
		loadIn($(elem), i);
	});

}

function loadIn(element, i){
	var delayInterval = 1500;
	
	setTimeout(function() {
		
		$(element).animate({
			opacity: 1
		}, 1500);
		
	}, (delayInterval * i));

	
}

$.fn.reorder = function() {
 
  // random array sort from
  // http://javascript.about.com/library/blsort2.htm
  function randOrd() { return(Math.round(Math.random())-0.5); }
 
  return($(this).each(function() {
    var $this = $(this);
    var $children = $this.children();
    var childCount = $children.length;
 
    if (childCount > 1) {
      $children.remove();
 
      var indices = new Array();
      for (i=0;i<childCount;i++) { indices[indices.length] = i; }
      indices = indices.sort(randOrd);
      $.each(indices,function(j,k) { $this.append($children.eq(k)); });
 
    }
  }));
}


function initPayPal(){

	$("#toggleShipping").colorbox({width:"300px", height: "540px", inline:true, href:"#shipping"});

	$("#submit_cart").click(function(e){
		e.preventDefault();
		//make sure all fields are filled out.
		var errors = 0;
		$("#shipping input").each(function(){
			if($(this).val() == ""){
				errors++;
			}
		});
		
		if(errors > 0){
			alert("Please make sure to fill out all delivery information fields!");
		} else {
			
			var form = $("#basket_items").attr('action', "index.php?&id=66");
			$(form).append($("#shipping"));
			$("#cboxLoadedContent").html("<div id='loading'>Loading - Please wait...</div>");
			//alert("HERE");
			$(form).trigger('submit');
		}
		
		
	});
	
	$('.pricing select').appendTo('#shipping_options');
	
	$('#state').change(function(){
		
		if($(this).val() == "HK"){
			$("#shipping_options select option").attr('selected', '');
			$("#shipping_options select option:eq(0)").attr('selected', 'selected');
		} else {
			$("#shipping_options select option").attr('selected', '');
			$("#shipping_options select option:eq(1)").attr('selected', 'selected');
		}
		
		setFullPrice();
	});
	
	
	
	setFullPrice();

}

function setFullPrice(){
	var price = parseFloat($("#subtotal span").text()) + parseFloat($('#shipping_options select').val());
	price = Math.round(price*100)/100;
	$('#full_total span').html(price);
	//get the option text
	var text = $('#shipping_options select option:selected').text();
	$("#show_shipping").html(text);
	
}

function initMailingList(){
	$("#mailing_list").submit(function(e){
		
		if($('#email_address').val() == ''){
			e.preventDefault();
			alert('Please supply an email address!');
		}
	});
}

$(window).load(function(){
	initHomepage();
	$("#indicators a:eq(0)").trigger('mouseenter');
	startCrossFade();
});

function initProductPage(){
	
	$("#add_to_cart").click(function(e){
		e.preventDefault();
		
		var errors = '';
		
		//check color and size are ok
		if($("#sizing select").val() == ""){
			errors = "Please select a size.";
		}
		
		if($("#colors select").val() == ""){
			errors = "Please select a color.";
		}
		
		var stockForColor = disabled[ $("#colors select").val() ];
		for(var x = 0; x < stockForColor.length; x++){
			if(stockForColor[x] == $("#sizing select").val()){
				errors = "Sorry, that size and color option is currently out of stock!";
			}
		}
		
		if(errors == ''){
			$(this).parents('form').trigger('submit');
		} else {
			alert(errors);
		}
		
	});
	
	$(".color_swab").each(function(i){
	
		$(this).click(function(e){
			y = i + 1;
			$("#colors option:eq(" + y + ")").attr('selected', 'selected');
		
			e.preventDefault();
			var id = $(".id", this).text();
			var name = $("h3", this).text();
			$('#chosen').val(id);
			$("#chosen_color").html(name);
		});
		
	});
	
	$("#color_options select").change(function(){
		var name = $("option:selected", this).text();
		if($("option:selected", this).val() == ""){
			$("#chosen_color").html('');
		} else {
			$("#chosen_color").html(name);
		}
		
	});
	
	$("#product_thumbs img").click(function(e){
		e.preventDefault();
		$("#product_shot a").html("<img src='web_assets/css/images/ajax-loader.gif' alt='' class='loading' />");
		
		var large = $(this).attr('longdesc');
		var newImage = new Image();
		newImage.src = large;
		$(newImage).load(function(){
		
			
		$("#product_shot a").html(newImage);
		
			
		});

		
	});
	
}



function view_more(doc_id){

	window.open(base_url + "index.php?id=59&target=" + doc_id, "view_more","menubar=0,resizable=1,scrollbars=1,width=1024,height=800"); 

}





function initHomepage(){
	

	$("#carousel .carousel_slide_indicator").each(function(i){
		$(this).click(function(e){
			e.preventDefault();
			clearInterval(flip);
		});
		
		$(this).hover(function(){
			selected = i;
			var id = "slide_" + $(this).attr('id');
			$(".carousel_slide:not('#" + id + "')").fadeOut('slow');
			$("#indicators a").removeClass('active');
			
			$("#" + id).fadeIn("slow");
			$(this).addClass('active');
		}, function(){
		
		});
	});
	
	$("#crossfader .loading").remove();
}

function updatePaginator(){
	
	$("#page_total").text($("#photos_small .photo img").length);
	
	$("#photos_small .photo img").each(function(i){
		if($(this).hasClass('active')){
			$("#page_current").text(i+1);
		}
	});
}



function initPopupGallery(){

	$("#DISABLEDphotos a:first").click(function(e){
		e.preventDefault();
		var link = $(this).attr('href');
		if($("#photos .icon_zoom").length > 0){
			$("#photos .icon_zoom").trigger('click');
		} else {
			window.open(link,"LargeImage","menubar=no,width=600,height=auto,toolbar=no");
		}
		
	});
	
	//var images = $("#photos_small img");
	//if(images.length <= 3){
		$("#popup .controls").hide();
	//}
	
	$("#popup .scroll_left").click(function(e){
		e.preventDefault();
	
	});
	
	$("#popup .scroll_right").click(function(e){
		e.preventDefault();
	
	});
	
	$("#photos_small img").click(function(e){
	
		e.preventDefault();
		var link = $(this).attr('longdesc');
		var clone = "<a title='Click for full view' href='" + link + "' target='_blank'><img src='" + link + "' /></a>";
		$("#photos_large").html(clone);
		$("#photos_small img").removeClass('active');
		$(this).addClass('active');
		
		updatePaginator();
		
	});
	
	$("#photos_small img:first").trigger('click');
	
	$("#detail_back").click(function(e){
		e.preventDefault();
		var selected = parseInt($("#page_current").text());
		
		if(selected == 1){
			index = $("#photos_small .photo img").length - 1;
		} else {
			index = selected - 1;
		}
		
		$("#photos_small .photo img:eq(" + index + ")").trigger('click');
		
	});
	
	$("#detail_forward").click(function(e){
		e.preventDefault();
		
		var selected = parseInt($("#page_current").text());
		
		if(selected == $("#photos_small .photo img").length){
			index = 0;
		} else {
			index = selected;
		}
		
		$("#photos_small .photo img:eq(" + index + ")").trigger('click');
		
	});
	
}







/**
* @author Remy Sharp
* @url http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/
*/

(function ($) {

$.fn.hint = function (blurClass) {
  if (!blurClass) { 
    blurClass = 'blur';
  }
    
  return this.each(function () {
    // get jQuery version of 'this'
    var $input = $(this),
    
    // capture the rest of the variable to allow for reuse
      title = $input.attr('title'),
      $form = $(this.form),
      $win = $(window);

    function remove() {
      if ($input.val() === title && $input.hasClass(blurClass)) {
        $input.val('').removeClass(blurClass);
      }
    }

    // only apply logic if the element has the attribute
    if (title) { 
      // on blur, set value to title attr if text is blank
      $input.blur(function () {
        if (this.value === '') {
          $input.val(title).addClass(blurClass);
        }
      }).focus(remove).blur(); // now change all inputs to title
      
      // clear the pre-defined text when form is submitted
      $form.submit(remove);
      $win.unload(remove); // handles Firefox's autocomplete
    }
  });
};

})(jQuery);