// main.js
// TODO: distribute page specific js code to new files
var arrPageSizes;

$(document).keydown( function( e ) {
	if( e.which == 27)
	{  // escape, close overlays
		overlay_out();
		$(".email_overlay, .email_page").hide();
	}
});
$(document).ready(function(){
	jQuery('#related_carousel').jcarousel();
	
	arrPageSizes = ___getPageSize();

	$("div.drop p").hover(
		function() {
			$(this).css("background-image", "url(img/bg_custom.gif)");
			$(this).css("background-repeat", "repeat-x");
		},
		function() {
			$(this).css("background", "none");
		}		
	);
	
	// ud temporary button

	$("#btn_ud_open").bind("click", function(){ ud_open(); });
	
	// forgot password
	$("#btn_forgotpass").bind("click", function(){
		$("#overlay_forgotpass_form").show();
		$("#overlay_forgotpass_thanks").hide();
		$("#overlay_forgotpass_message").text('Please enter your email below...');
		overlay_in();
		$("#overlay_forgotpass").css('top', window.pageYOffset + 150);
		$("#overlay_forgotpass").show();
		return false;
	});
	
	$("#btn_cancel_forgotpass, #btn_close2_forgotpass").bind("click", function(){
		 overlay_out();
		 $("#overlay_forgotpass").hide();
		 return false;
	});
	
	$("#btn_send_forgotpass").bind("click", function(){
		$("#overlay_forgotpass_message").text('Processing...');
		email = $("#overlay_forgotpass_email").val();
		$.ajax({
			url : "/index.php?ajaxrequest=forgot-password&email=" + email,
			success : function (data) {
			   if(data=="OK") { 
   				$("#overlay_forgotpass_form").hide();
				$("#overlay_forgotpass_thanks").show();
			   } else {
				$("#overlay_forgotpass_message").html(data);  
			   }
			}
		});
		return false;
	});	
	
	// wishlist submit
	$("#btn_wishlist").bind("click", function(){
		add_to_wishlist();
		overlay_in();
		$("#overlay_wishlist").css('top', window.pageYOffset + 150 );
		$("#overlay_wishlist").show();
		return false;
	});
	
	$("a#btn_remove_from_wishlist").bind("click", function(){
		remove_from_wishlist();
		overlay_in();
		$("#overlay_wishlist").css('top', window.pageYOffset + 150 );
		$("#overlay_wishlist").show();
		return false;
	});	
	
	$("#btn_close_wishlist").bind("click", function(){
		 overlay_out();
		 $("#overlay_wishlist").hide();
		 return false;
	});
	
	$(".btn_discounts").bind("click", function(){
		overlay_in();		
		$("#overlay_discounts").css('top', window.pageYOffset + 150 );
		$("#overlay_discounts").show();
		return false;
	});
	
	$("#btn_close_discounts").bind("click", function(){
		 overlay_out();
		 $("#overlay_discounts").hide();
		 return false;
	});
	
	$(".btn_feature").bind("click", function(){
		$.ajax({
			url : "/index.php?ajaxrequest=product-feature&feature=" + $(this).attr('rel'),
			success : function (data) {
				$("#feature_info").html(data);
				$("#overlay_feature").show();
			}
		});
		overlay_in();
		$("#overlay_feature").css('top', window.pageYOffset + 150 );
		$("#overlay_feature > div").removeClass("overlay-login-wide");

		$("#overlay_feature #feature_title").html($(this).attr('rel').toUpperCase());
		if ($(this).attr('rel') == "Factory Direct")
		{
			$("#overlay_feature > div").addClass("overlay-login-wide");
			$("#overlay_feature").css("width", "auto");
			$("#overlay_feature").css("left", "136px");
		}
		else
			$("#overlay_feature").css("left", "");
		Cufon.refresh();
		return false;
	});
	
	$("#btn_close_feature").bind("click", function(){
		 overlay_out();
		 $("#overlay_feature").hide();
		 return false;
	});
	
	/* wishlist page */
	$(".btn_submit_wishlist").bind("click", function(){
		overlay_in();
		if(wishlistcount == 0)
		{
			$("#wishlist_add_info").text('Your wishlist is empty');
			$("#overlay_wishlist").css('top', window.pageYOffset + 150 );
			$("#wishlist_title").text('WISHLIST EMPTY');
			Cufon.replace('h2');
			$("#overlay_wishlist").show();			
		}
		else
		{
			if(loggedin)
			{
				$("#btn_wishlistsubmit_submit").show();				
				$("#wishlist_submit_info").text('Submit your wishlist to the sales department?');
				$("#btn_wishlistsubmit_submit").attr('class','btn_submit');
			}
			$("#overlay_wishlistsubmit").css('top', window.pageYOffset + 150 );
			$("#overlay_wishlistsubmit").show();
		}
		return false;
	});
	
	$("#btn_wishlistsubmit_cancel").bind("click", function(){
		overlay_out();		
		$("#overlay_wishlistsubmit").hide();
		return false;
	});
	
	$("#btn_wishlistsubmit_submit").bind("click", function(){
		if(loggedin == 0){
			uri = encodeURIComponent(window.location.href)
			location.href = '/login.html?loginfrom=wishlist.html';
		} else {
			submit_wishlist();
		}
		return false;
	});
}
);

function overlay_in()
{
	$('#jquery-overlay').css({
			backgroundColor:	'#000',
			opacity:			0.8,
			width:				arrPageSizes[0],
			height:				arrPageSizes[1]
	}).fadeIn();
}

function overlay_out(cb)
{
	$('#jquery-overlay').fadeOut(function() { $('#jquery-overlay').hide(); if (cb) cb(); });
}

function submit_wishlist(clear)
{
	$.ajax({
			url : "/index.php?ajaxrequest=submit-wishlist&memberid=" + memberid + "&clear=" + clear,
			success : function (data) {
			   if(data=="OK")
			   { 
   					$("#wishlist_submit_info").text('Wishlist was submitted');
					$("#btn_wishlistsubmit_cancel").attr('class','btn_close');
					$("#btn_wishlistsubmit_cancel").bind("click", function(){
						window.location.reload ( );
					});
					$("#btn_wishlistsubmit_submit").hide();
			   }
			   else
			   {
					$("#wishlist_submit_info").text(data);
			   }
			}
	});
}

function remove_from_wishlist()
{
	$.ajax({
		url: "/index.php?ajaxrequest=remove-from-wishlist&productid=" + productid,
		type: "GET",
		success: function( data ) {
			$("#wishlist_add_info").text(data);
			$("#wishlist_title").text('REMOVED FROM WISHLIST');
			Cufon.replace('h2');
			$("a#btn_remove_from_wishlist").addClass('hidden');
			var qtcols = $(".colors").find(".qtcolumn");
			for(var i = 0; i < (qtcols.length - 1); i++)
			{
				$(qtcols[i]).remove();
			}
		}
	});
}

function add_to_wishlist()
{
	var xmlDoc = '<?xml version="1.0"?><wishlist productid="' + productid + '">';
	var qtcols = $(".colors").find(".qtcolumn");
	var allfields = [];
	var error = false;
	var nonzero = false;
	
	for(var i = 0; i < qtcols.length; i++)
	{
		var column = qtcols[i];
		
		var color = $(column).find(".colorselector").text();
		
		xmlDoc += '<column id="' + i + '" color="' + color + '">';
		
		var fields = $(column).find(".qtinput");
		
		for(var j = 0; j < fields.length; j++)
		{
			var field = fields[j];
			var value = $(field).val();
			var name = $(field).attr('name');
			if(value != '' && value > 0)
			{
				xmlDoc += '<field id="' + name + '" value="' + value + '"/>';
				nonzero = true;
				if(color == 'Pick Color')
					error = true;
			}
		}
		if(!nonzero)
		{
			error = true;
		}
		xmlDoc += '</column>';
	}
	
	xmlDoc += '</wishlist>';

	if(error)
	{
		$("#wishlist_add_info").text("Please pick a color and fill in the desired quantity in all columns.");
		$("#wishlist_title").text('ADD TO WISHLIST');
		Cufon.replace('h2');
	}
	else
	{
		$.ajax({
			url: "/index.php?ajaxrequest=add-to-wishlist",
			type: "POST",
			processData: false,
			contentType: "text/xml",
			data: xmlDoc,
			success: function( data ) {
				$("#wishlist_add_info").text(data);
				$("#wishlist_title").text('ADDED TO WISHLIST');
				Cufon.replace('h2');
				wishlistcount = 1;
			}
		});
		$("#btn_wishlist").attr('class','save');
		$("a#btn_remove_from_wishlist").removeClass('hidden');
	}
}

$.createXMLDocument = function( s )
{
	var browserName = navigator.appName;
	var xmlDoc;
	if ( browserName == "Microsoft Internet Explorer" )
	{
		xmlDoc = new ActiveXObject( "Microsoft.XMLDOM" );
		xmlDoc.async = "false";
		xmlDoc.loadXML( s );
	}
	else
	{
		xmlDoc = ( new DOMParser() ).parseFromString( s, "text/xml" );
	}
	return xmlDoc;
}


$(window).resize(function() {
	get_page_sizes();
});

function get_page_sizes()
{
	var arrPageSizes = ___getPageSize();

	$('#jquery-overlay').css({
		width:		arrPageSizes[0],
		height:		arrPageSizes[1]
	});
}

function insert_color_dropdown(element)
{
	var newcolumn = $(element).parent().clone(true).insertAfter($(element).parent()); // clone the form
	$(newcolumn).find(".colorselector").prev().remove();
	$(newcolumn).children(".bg_shadow").children("li").children("input").val('');
	$(newcolumn).find(".colorselector").text('Pick Color');	

	if ($("p", $(newcolumn)).length == 1)
		$("p", $(newcolumn)).click();

	recount_qt(newcolumn);
}

function emptyexists()
{
	var emptyfound = false;
	var qtcols = getElementsByClassName("bg_shadow");
	for(var i = 0; i <= qtcols.length; i++)
	{
		var column = qtcols[i];
		if($(column).find(".qtsum").val() == '0')
		{
			emptyfound = true;
		}
	}
	return emptyfound;
}

function recount_qt(column)
{
	var sum = 0;
	$(column).find(".qtinput").each(function (i)
	{
		if($(this).val() != '')
		{
			var val = parseInt($(this).val());
			if (!isNaN(val))
				sum += val;
		}
	});
	$(column).find(".qtsum").val(sum);
}

function init_color_dropdowns()
{
	$(".drop").hide();
	var selectors = getElementsByClassName("colorselector");
					
	for(var i = 1; i <= selectors.length; i++)
	{
		var trigger = "#sel_color" + (i);
		var target = "#drop" + (i);

		$(trigger).bind("click", function(){
			$(this).next().toggle();
		});

		$(target + " p").bind("click", function(){ // Color select
			//$(this).parent().prev().text($(this).children("span").html());
			$(this).parent().prev().text($(this).children("span").attr("title"));
			// Size availability check
			var element = $(this).parent().parent().parent().parent();
			
			//check_available_sizes(element, $(this).children("span").html());
			check_available_sizes(element, $(this).children("span").attr("title"));
			$(this).parent().parent().find(".dynamic_colorbox").remove();
			$(this).find("img").clone(true).prependTo($(this).parent().parent()).addClass("dynamic_colorbox");
			$(this).parent().hide();
		});

/*		$(trigger).parent().parent().parent("li .qtinput").bind("change", function(){
			recount_qt(this);
			if(emptyexists() != true){
				insert_color_dropdown($(this));

			}					
		});*/

		$(trigger).parent().parent().parent().children(".remove").children(".col_remove").bind("click", function(){
			if($(this).parent().parent().parent().parent().children().size() > 1 && emptyexists()) {
				$(this).parent().parent().parent().remove();
			}
			return false;
		});
	}
	
	var qtcolumns = getElementsByClassName("qtcolumn");
					
	for(var i = 0; i < qtcolumns.length; i++)
	{
		$(qtcolumns[i]).find(".qtinput").bind("change", function(){
			var qtcol = $(this).parent().parent();
			recount_qt(qtcol);
			if(emptyexists() != true){
				insert_color_dropdown($(qtcol));
			}					
		});
	}
}

function check_available_sizes(element, color)
{
	$.ajax({
		url : "/index.php?ajaxrequest=available-sizes&color=" + color + "&productid=" + productid,
		success : function (data) {
		   if(data=="ERROR")
		   { 
				
		   }
		   else if(data != "")
		   {
				element.children("li").children("input").attr("disabled","");
				if(data != 'ENABLE_ALL')
				{
					element.children("li").children(data).attr("disabled","disabled");
					element.children("li").children(data).val("");
				}
				recount_qt(element);
		   }
		}
	});	
}

function ___getPageSize() {
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
	return arrayPageSize;
};



// various helper functions

/*
	Developed by Robert Nyman, http://www.robertnyman.com
	Code/licensing: http://code.google.com/p/getelementsbyclassname/
*/	
var getElementsByClassName = function (className, tag, elm){
	if (document.getElementsByClassName) {
		getElementsByClassName = function (className, tag, elm) {
			elm = elm || document;
			var elements = elm.getElementsByClassName(className),
				nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
				returnElements = [],
				current;
			for(var i=0, il=elements.length; i<il; i+=1){
				current = elements[i];
				if(!nodeName || nodeName.test(current.nodeName)) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	else if (document.evaluate) {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = "",
				xhtmlNamespace = "http://www.w3.org/1999/xhtml",
				namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
				returnElements = [],
				elements,
				node;
			for(var j=0, jl=classes.length; j<jl; j+=1){
				classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
			}
			try	{
				elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
			}
			catch (e) {
				elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
			}
			while ((node = elements.iterateNext())) {
				returnElements.push(node);
			}
			return returnElements;
		};
	}
	else {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = [],
				elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
				current,
				returnElements = [],
				match;
			for(var k=0, kl=classes.length; k<kl; k+=1){
				classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
			}
			for(var l=0, ll=elements.length; l<ll; l+=1){
				current = elements[l];
				match = false;
				for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
					match = classesToCheck[m].test(current.className);
					if (!match) {
						break;
					}
				}
				if (match) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	return getElementsByClassName(className, tag, elm);
};