/*
	Copyright DTDigital		 :: www.dtdigital.com.au ::
	Unauthorised modification / use is a criminal offence, and
	will be prosecuted to the fullest extent permitted by law.
	All Rights Reserved
*/


function ddRedirect(dd)
{
	if (dd.options[dd.selectedIndex].value != "") self.location = dd.options[dd.selectedIndex].value;
}

var userAgent = navigator.userAgent;
var isIE5 = (userAgent.indexOf("MSIE 5") != -1);

function opencart(url, productItemID, quantityBox, storeType)
{
	if(!IsNumeric(document.getElementById(quantityBox).value) || document.getElementById(quantityBox).value == '')
	{
		alert('Invalid quantity');
	}
	else if (isIE5)
	{
		document.location = url;
	}
	else
	{
		quantity = document.getElementById(quantityBox).value;

		tb_show("Add product to cart", "products_add-to-cart.aspx?ProductItemID=" + productItemID + "&Quantity=" + quantity + "&store=" + storeType + "&TB_iframe=true&height=330&width=400", "");
	}
}

function opencollectioncart(url, productItemID, quantityBox, storeType, collectionID)
{
    if (!IsNumeric(document.getElementById(quantityBox).value) || document.getElementById(quantityBox).value == '')
    {
        alert('Invalid quantity');
    }
    else if (isIE5)
    {
        document.location = url;
    }
    else
    {
        quantity = document.getElementById(quantityBox).value;

        tb_show("Add product to cart", "products_add-to-cart.aspx?ProductItemID=" + productItemID + "&Quantity=" + quantity + "&store=" + storeType + "&CollectionID=" + collectionID + "&TB_iframe=true&height=330&width=400", "");
    }
}

function removeitem(url, cartItemIndex, storeType)
{
	if (isIE5)
	{
		document.location = url;
	}
	else
	{
		tb_show("Remove item from cart", "cart_remove-product.aspx?CartItemIndex=" + cartItemIndex + "&store=" + storeType + "&TB_iframe=true&height=330&width=400", "");
	}
}

function removecollectionitem(url, cartItemIndex, storeType, collectionID)
{
    if (isIE5)
    {
        document.location = url;
    }
    else
    {
        tb_show("Remove item from cart", "cart_remove-product.aspx?CartItemIndex=" + cartItemIndex + "&store=" + storeType + "&CollectionID=" + collectionID + "&TB_iframe=true&height=330&width=400", "");
    }
}

function removegreetingcarditem(url, cartItemIndex, storeType)
{
	if (isIE5)
	{
		document.location = url;
	}
	else
	{
		tb_show("Remove item from cart", "cart_remove-product.aspx?removegreetingcarditem=" + cartItemIndex + "&store=" + storeType + "&TB_iframe=true&height=330&width=400", "");
	}
}

function clearall(url, storeType)
{
	if (isIE5)
	{
		document.location = url;
	}
	else
	{
		tb_show("Remove all items from cart", "cart_clear.aspx?store=" + storeType + "&height=330&width=400&TB_iframe=true", "");
	}
}

function clearallcollection(url, storeType, collectionID)
{
    if (isIE5)
    {
        document.location = url;
    }
    else
    {
        tb_show("Remove all items from cart", "cart_clear.aspx?store=" + storeType + "&CollectionID=" + collectionID + "&height=330&width=400&TB_iframe=true", "");
    }
}


function closecart()
{
	tb_remove2();
}

function closecart2()
{
    tb_remove();
}

// Works out inner widths of browser and sets width of div
function DTDockW()
{
	var viewportWidth = document.body.clientWidth;
	var Dock = document.getElementById("dtdock");

	if(Dock)
	{
		Dock.style.width = viewportWidth + 16 + "px";

		//document.getElementById("body").style.padding = "0 0 40px 0";

		// Adjusts width for IE6
		if(navigator.userAgent.indexOf("MSIE 6") != -1)
		{
			Dock.style.width = viewportWidth + "px";
		}

		// Checks if inner widths is below 800x600 resolution and sets it to 780px
		if(viewportWidth < 780)
		{
			Dock.style.width = "770px";
		}
	} else {
		return false;
	}
}


window.onresize = DTDockW;

// Minimising dock
function shrink()
{
    if (document.getElementById("dtdock"))
    {
	    document.getElementById("dtdock").className = "dtdock_shrink";
	}

	if (document.getElementById("body"))
	{
	    document.getElementById("body").style.padding = "0 0 6px 0";
	}
}
// Maximising dock
function grow()
{
    if (document.getElementById("dtdock"))
    {
        document.getElementById("dtdock").className = "dtdock_grow";
    }

    if (document.getElementById("body"))
    {
        document.getElementById("body").style.padding = "0 0 112px 0";
    }
}

// IFrame Scrolling functions
var timer_id;

function scroll_iframe(frm, h, v) {
  if (timer_id) clearTimeout(timer_id);

  if (window.frames[frm]) {
		window.frames[frm].scrollBy(h, v);

	timer_id = setTimeout("scroll_iframe('" + frm + "', '" + h + "', '" + v + "')", 20);
  }
}

function stopScroll() {
	if (timer_id) clearTimeout(timer_id);
}

/**
 * Sets a Cookie with the given name and value.
 *
 * name	   Name of the cookie
 * value	  Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]	 Path where the cookie is valid (default: path of calling document)
 * [domain]   Domain where the cookie is valid
 *			  (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *			  secure transmission
 */
function setCookie(name, value, expires, path, domain, secure) {
	document.cookie= name + "=" + escape(value) +
		((expires) ? "; expires=" + expires.toGMTString() : "") +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "");
}

/**
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
function getCookie(name) {
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	} else {
		begin += 2;
	}
	var end = document.cookie.indexOf(";", begin);
	if (end == -1) {
		end = dc.length;
	}
	return unescape(dc.substring(begin + prefix.length, end));
}

/**
 * Deletes the specified cookie.
 *
 * name	  name of the cookie
 * [path]	path of the cookie (must be same as path used to create cookie)
 * [domain]  domain of the cookie (must be same as domain used to create cookie)
 */
function deleteCookie(name, path, domain) {
	if (getCookie(name)) {
		document.cookie = name + "=" +
			((path) ? "; path=" + path : "") +
			((domain) ? "; domain=" + domain : "") +
			"; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
}

function dockstate()
{
	var state = getCookie('state')

	if (state == 'hidden')
	{
	    if (document.getElementById("dtdock"))
	    {
	        document.getElementById("dtdock").style.display = "none";
	    }
	}
	if (state == 'visible')
	{
        if (document.getElementById("dtdock"))
        {
            document.getElementById("dtdock").style.display = "block";
        }
        
        shrink();
	}
	if (state == 'expanded')
	{
	    if (document.getElementById("dtdock"))
	    {
	        document.getElementById("dtdock").style.display = "block";
	    }
	    
        grow();
	}
}

// Below functions do all states of dock and store value of state in cookie.
function opendock()
{
	shrink();
	setCookie('state', 'visible');
	dockstate();
}
function minimisedock()
{
	shrink();
	setCookie('state', 'visible');
	dockstate();
}
function maximisedock()
{
	grow();
	setCookie('state', 'expanded');
	dockstate();
	reloaddock();
}
function closedock()
{
	setCookie('state', 'hidden');
	dockstate();
}
function reloaddock()
{
	document.getElementById('cartdock').contentWindow.location.reload();
}
////////////////////////////////////


/*********************************************************
***************** Client Side Validation *****************
*********************************************************/

function cartshippingitemvalidate(index, validationsummaryid)
{
	var el = document.getElementById("address" + index);

	var divs = el.getElementsByTagName("div");

	var errormessages = "";

	for (i=0; i<divs.length; i++)
	{
		// loops through all div inside id address + index div and checks to see if it has class required on it.
		if (divs[i].className.indexOf("required") != -1)
		{
			// Looks for all inputs and checks if they are empty, if so adds class cerror to parent div of field
			var inputs = divs[i].getElementsByTagName("input");
			for (a=0; a<inputs.length; a++)
			{
				if(inputs[a].value == "")
				{
					divs[i].className += " cerror";
					errormessages += "<li>" + inputs[a].title + "</li>";
				}
			}
			// Looks for all selects and checks if they are empty, if so adds class cerror to parent div of field
			var selects = divs[i].getElementsByTagName("select");
			for (b=0; b<selects.length; b++)
			{
				if(selects[b].value == "")
				{
					divs[i].className += " cerror";
					errormessages += "<li>" + selects[b].title + "</li>";
				}
			}
			// Looks for all textareas and checks if they are empty, if so adds class cerror to parent div of field
			var textareas = divs[i].getElementsByTagName("textarea");
			for (c=0; c<textareas.length; c++)
			{
				if(textareas[c].value == "")
				{
					divs[i].className += " cerror";
					errormessages += "<li>" + textareas[c].title + "</li>";
				}
			}
		}
	}

	if(errormessages == "")
	{
		// Checks if error message string is empty and hides error summary box then returns true for server side
		document.getElementById("errors" + index).style.display = "none";
		return true;
	}
	else
	{
		// Hides server side validation summary
		document.getElementById(validationsummaryid).style.display = "none";
		// Displays client side validation summary
		document.getElementById("errors" + index).style.display = "inline";
		// Writes in the html for client side validation
		document.getElementById("errors" + index).innerHTML = "<div class='errors'> <ul>" + errormessages + "</ul> </div>";

		// Checks to see if there is only one error message and adds class to increase padding of summary box
		if(document.getElementById("errors" + index).getElementsByTagName("li").length == 1)
		{
			document.getElementById("errors" + index).className = "oneerror";
		} else {
			document.getElementById("errors" + index).className = "";
		}
		return false;
	}
}

function clearvalidation(obj)
{
	if (obj.value != "")
	{
		obj.parentNode.className = "field required";
	}
}

function cleardefaultvalue(obj, defaultval)
{
	if (obj.value == defaultval)
	{
		obj.value = "";
	}
}
function resetdefaultvalue(obj, defaultval)
{
	if (obj.value == "")
	{
		obj.value = defaultval;
	}
}

function restricttextarea(obj, index)
{
	maxlength = 256;

	if (obj.value.length > 256)
	{
		obj.value = obj.value.substring(0, maxlength);
	}
	else
	{
		document.getElementById("counter" + index).innerHTML = maxlength - obj.value.length;
	}
}
function changeBG(index)
{
	document.getElementById("TB_closeWindowButton").style.background = "url(assets/Thickbox/close_" + index + ".gif) 0 0 no-repeat";
}


/*
	4 State Navigation Menu.
*/
$(document).ready(function(){

	resizeNavMenuBox();
	ProductScrollerStates();
	FooterScrollerResize();
	FooterScroller();
	
	// Custom font replacements
	cufonReplacements();

	//IE6 iframe fix.
	$("#link03,#box03,#link04,#box04,#link05,#box05").hover(function (){$("iframe").css("visibility", "visible");}, function (){$("iframe").css("visibility", "hidden");});

	//Hover states for images/buttons. (Add class "hover-input" to element).
	$(".hover-input").each(function()
	{
		var imageSrc = $(this).attr("src");
		var imageName = imageSrc.substring(imageSrc.lastIndexOf("swap_") + 5, imageSrc.lastIndexOf("_"));
		
		//alert(imageSrc);
		var locCheck = imageSrc.search('_2') != -1;
		
		var offState = "assets/swap_"+imageName+"_0.gif"; //2 state hovers
		var onState = "assets/swap_"+imageName+"_1.gif";
		
		var offState2 = offState.replace(/_0.gif/g, "_2.gif"); //4 state hovers
		var onState2 = onState.replace(/_1.gif/g, "_3.gif");
		
		$(this).mouseover(function()
		{
			//alert(locCheck);
			if(locCheck == true){
				$(this).attr("src", onState2);
			}
			else {
				$(this).attr("src", onState);
			}
			
		});
		
		$(this).mouseout(function()
		{
			if(locCheck == true){
				$(this).attr("src", offState2);
			}
			else {
				$(this).attr("src", offState);
			}
		});

	});
	
});

function IsNumeric(sText)
{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
}

function resizeNavMenuBox(){
	$(".navmenu .box").removeClass("defaultbox");
	$(".navmenu .box").each(function(){
		var colNumber = parseInt($(this).find(".col").size());	
		var colWidth = parseInt($(".col").width()) + 22;
		if(colNumber < 5){
			var boxWidth = (colNumber * colWidth) + 5;
		} else {
			var boxWidth = (4 * colWidth) + 5;
		}
		$(this).width(boxWidth).css("width", boxWidth+"px");
	});
}

/** Product Popup Tip JScript **/
function CreatePopupTip(id){
	var popupTip;
	if(id != undefined){
		popupTip = '<div class="popuptip" id="'+id+'"><div class="popupcontent">Product Title</div></div>';
	} else {
		popupTip = '<div class="popuptip"><div class="popupcontent">Product Title</div></div>';
	}
	$(popupTip).prependTo("body");
}
function RemovePopupTip(){
	$(".popuptip").remove();	
}

function ProductScrollerStates() {
	var checkProductPopup = $(".othergifts ul li, .edit-link").size();
	if(checkProductPopup != 0){	
		$(".othergifts ul li a").attr("title", "");
		$(".othergifts ul li a img").attr("alt", "");
		$(".othergifts ul li, .edit-link").hover(function(){		
			CreatePopupTip();
			var getProductTitle;
			var getThis = $(this).attr("class");
			if(getThis != "edit-link"){
				getProductTitle = $(this).find("span").html();
			} else {
				getProductTitle = $(this).attr("title");
			}
			$(".popupcontent").html(getProductTitle);
			$(this).mousemove(function(e){
				var x = e.pageX - ($(".popuptip").width() / 2);
				var y = e.pageY - ($(".popuptip").height() + 10);
				$(".popuptip").css({"display" : "block", "top" : y, "left" : x});
			});
		}, function(){	
			RemovePopupTip();
		});
	}
	
	var checkScrollerPopup = $(".thumb-gallery a, .inner-container a").size();
	if(checkScrollerPopup != 0){	
		$(".thumb-gallery a, .inner-container a").hover(function(){	
			$(this).attr("title", "");
			$(this).find("img").attr("alt", "");
			
			CreatePopupTip("designertip");
			
			var getProductTitle2 = $(this).find(".hidden").text();
			$(".popupcontent").html("<strong>"+getProductTitle2+"</strong>");

			var titleLength = getProductTitle2.length;
			if(titleLength != 0 && getProductTitle2 != " "){
				$(this).mousemove(function(e){
					var x = e.pageX - ($(".popuptip").width() / 2);
					var y = e.pageY - ($(".popuptip").height() + 10);
					$(".popuptip").css({"display" : "block", "top" : y, "left" : x});
				});
			}
		}, function(){	
			RemovePopupTip();
		});
	}
}

function cufonReplacements() {
	Cufon.now();
	
	var checkh3 = $('.collection-container h3').size();
	
	if(checkh3 != 0){
		Cufon.replace('.collection-container h3', { fontFamily: 'Myriad-Light' });
		$("span.cufon.cufon-canvas:not(strong + span.cufon.cufon-canvas)").each(function(){
			var checkEmptyStr = $(this).find(".cufon-alt").text();
			if (checkEmptyStr == " "){
				$(this).remove();
			}
		});
	}
}

/** Designer Collections JScript **/

function FooterScroller() {
	
	//Hover animations for thumbnails.
	$(".footer-scroller, .containerspace").css("display", "block");
	
	$(".outer-container").css("overflow", "hidden");
	
	$(".inner-container a:not(.active)").find("img").fadeTo(0.1, 0.4);

	$(".inner-container a img").hover(function(){
		$(this).stop().fadeTo(150, 1);									   
	}, function(){
		var checkActive = $(this).parent().attr("class");
		if(checkActive != "active"){
			$(this).stop().fadeTo(150, 0.4);
		}
	});
}

function FooterScrollerResize() {
	
	//Resize Scroller when window dimensions change.
	var windowWidth = $(window).width();
	var windowHeight = $(window).height();
	
	if(windowWidth < 1016){
		$(".footer-scroller, .collection#bodycontainer").addClass("limitwidth");
	} else {
		$(".footer-scroller, .collection#bodycontainer").removeClass("limitwidth");
	}
	
	if(windowHeight > 593){
		$(".footer-scroller").css("position", "absolute");
		$(".collection-container").addClass("type02");
		$(".containerspace").css("display", "block");
	} else {
		$(".footer-scroller").css("position", "relative");	
		$(".collection-container").removeClass("type02");
		$(".containerspace").css("display", "none");
	}
	
	
	
}

$(function(){	
	var checkFooterScroller = $(".footer-scroller").size();
	
	if(checkFooterScroller != 0){
		FooterScrollerResize();
		$(window).bind('resize', function() { //Calls functions on Window resize
			FooterScrollerResize();
		});
	}
});
