// JavaScript Document
var loadspan = '<span class=\"wait\">Please Wait...</span>';

function category_redraw(n,v){
	if (n=='c_ppg') { c_spt = 1; }
	eval(n+'='+v); loadpage('/category.view/'+c_cid+'/'+c_spt+'/'+c_ppg+'/'+c_clr+'/'+c_thm+'/'+c_art+'/'+c_srt+'/'+c_md+'/0','#itemcontainer');
} 
function design_redraw(n,v){
	if (n=='c_ppg') { c_spt = 1; }
	eval(n+'='+v); loadpage('/designs.view/'+c_qft+'/'+c_spt+'/'+c_ppg+'/'+c_srt+'/'+c_clr+'/'+c_thm+'/'+c_art+'/0','#listcontainer');
}  

function category_reset(){
	$('#filterform select').val(0);
	loadpage('/category.view/'+c_cid+'/'+c_spt+'/'+c_ppg+'/0/0/0/'+c_srt+'/'+c_md+'/0','#itemcontainer');
} 
function design_reset(){
	$('#filterform select').val(0);
	loadpage('/designs.view/'+c_qft+'/'+c_spt+'/'+c_ppg+'/'+c_srt+'/0/0/0/0','#listcontainer');
}  

function livehelp() {
	try{ $('li.livehelp div a').click(); }
	catch(e) { self.location='mailto:support@decalgirl.com'; }
	return;
}

function oldloadpage(url,cont){
	$(cont).load(url);
}

function loadpage(url,cont){
	window.location = url;
}

function isdefined(object, variable){return (typeof(eval(object)[variable]) != 'undefined');}
function isemail(val) {if (val.match(/^([a-zA-Z0-9])+([.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-]+)+/)){return true;} else{ return false;}}
function num(n) { if ((n==null) || (n == '-')) { return 0;} else { return parseFloat(n.replace(/[^\d\.-]/g,'')); }}
function isdate(str) { splitDate = str.split("/");  if (splitDate[2] && splitDate[2].length == 2){splitDate[2] = "20"+splitDate[2]}; refDate = new Date(splitDate[1]+"/"+splitDate[0]+"/"+splitDate[2]); if (splitDate[1] < 1 || splitDate[1] > 12 || refDate.getDate() != splitDate[0] || splitDate[2].length != 4 || (!/^20/.test(splitDate[2]))) { return false } else { return true } }

function submitfailure() { showformerror('An transport error occurred while saving your information.'); }
function evalcallback(j) { if(j) { eval(j.DATA.CALLBACK[0]); } else { showformerror('An transport error occurred while saving your information.'); } }
function clearformerror() { $('.errorline').html(''); $('.errorline').hide(); }
function showformerror(err) { $('.errorline').html(err); $('.errorline').fadeIn(function(){$('.errorline').fadeOut(function(){$('.errorline').fadeIn()})}); }
function showloading() { $('.errorline').html(loadspan); $('.errorline').fadeIn(); }
function getmonthname(n) { var m = ['January','February','March','April','May','June','July','August','September','October','November','December']; return m[n-1]; } 

function gosecure(u) { self.location = secureURL + u; }
function goto(u) { self.location = baseURL + u; }

function show_modal_login() {
	load_modal_data('ShowLoginLogout');
}

function show_modal_logout() {
	load_modal_data('ShowLogout');
}

function headersearch() {
	if ($('#header-search #searchterm').val() != 'Search For...') {
		$('#header-search').submit();
	}
}

function process_modal_template(d) {
	if (arguments.length) {
		$('#modal div.header h5').html(d.DATA.HEADER[0]);
		$('#modal div.canvas').html(d.DATA.CANVAS[0]);
		$('#modal div.button-set span').html(d.DATA.BUTTONS[0]);
		$('#modal div.button-set p.modalerror').html(d.DATA.ERROR[0]);
		eval(d.DATA.CALLBACK[0]);  
	}
	$('.window .canvas').show();  	
	$('.window .loading').hide();  	
}

function show_modal_error(err) { 
	if (!arguments.length) { err = 'An transport error occurred.'; }
	$('.window .canvas').show();$('.window .loading').hide();$('.modalerror').html(err); $('.modalerror').fadeIn(function(){$('.modalerror').fadeOut(function(){$('.modalerror').fadeIn()})}); 
}


function load_modal_data(m) {
	$('.window .canvas').hide();  	
	$('.window .loading').show();  	
	show_modal_window('#modal');
	var current_modal_content = $('#modal div.button-set span').attr('class');
	if(current_modal_content!=m){
		$('#modal div.button-set span').attr('class',m);
		$.getJSON("assets/ajax/account.cfc", { method: m, returnformat : 'json', queryformat : 'column' }, function(j) {
			process_modal_template(j);
		});
	} else { 
		process_modal_template();
	}
}
	
	
function perform_modal_login() {
	var param1 = $("#mlogin input").serialize();
	var params = param1 + '&method=TryModalLogin&returnformat=json&queryformat=column';
	$.ajax({ type: 'post', url: '/assets/ajax/account.cfc', data: params, dataType: 'json', success: process_modal_login, failure:show_modal_error });
	$('.window .canvas').hide();  	
	$('.window .loading').show();  	
}

function perform_modal_logout() {
	$('.window .canvas').hide();  	
	$('.window .loading').show();  	
	$.getJSON("assets/ajax/account.cfc", { method: 'HandleLogout', returnformat : 'json', source_url: document.location.href, queryformat : 'column' }, function(j) {
		if(j.ROWCOUNT == 1) {
			$("li#greeter").html(j.DATA.GREETING[0]);	
			eval(j.DATA.CALLBACK[0]);
			hide_modal_window();
		}
	});	
}

function process_modal_login(j) { 
	if(j.DATA.HEADER[0]!='') { process_modal_template(j); } else if(j.DATA.CALLBACK[0]!='') { eval(j.DATA.CALLBACK[0]); } else { show_modal_error(); } 
}

	
function hide_modal_window() {
	$('#overlay').hide();  
	$('.window').hide();  
}

function show_modal_window(id) { 
	var maskHeight = $(document).height();  
	var maskWidth = $(window).width();  
    $('#overlay').css({'width':maskWidth,'height':maskHeight});  
	$('#overlay').fadeTo('slow',0.7);
	var winH = $(window).height();  
	var winW = $(window).width();  
	$(id).css('top',  winH/2-$(id).height()/2);  
	$(id).css('left', winW/2-$(id).width()/2);  
    $(id).fadeIn('slow');   
}

function currencyformat(c){
    var i = parseFloat(c);
	if(isNaN(i)) { i = 0.00; }
	var minus = '$';
	if(i < 0) { minus = '-$'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
};

function IsPositiveNumber(n) {
	var hasDot = 0; var numDecimals = 0; var goodNum = true;
	for (c = 0; n.length > c; c++) {
		var t = n.charAt(c);
		if ((isNaN(t)) && (t != '.') && (t != '$')) { goodNum = false; break; }
		if (t == '.') { 
			hasDot++; 
			if ((hasDot >= 2) || (n.length - (c + 1) >= 3)) { goodNum = false; break; }
		}
	}
	return goodNum;
}

function IsNumber(c) {
	var goodNum = true;
	var myRegEx = /^[1-9]\d{0,1}(\.\d{1,3})?$/
	if (c.search(myRegEx)==-1) {
		goodNum	= false;
	}
	return goodNum;
}

function gridcombo(dm1,dm2,dp,gridid) {
	this.dim1value = dm1;
	this.dim2value = dm2;
	this.saleprice = dp;
	this.gridid = gridid;
	return this;
}

function findgrid(d1,d2,ga) {
	for (var e=0;e<ga.length;e++){
		//alert(d1 == g[e].dim1value);
		if((d1 == ga[e].dim1value) && (d2 == ga[e].dim2value)) {
			return ga[e];
			break;	
		}
	}
	return null;
}

function gotoitem(i) {
	self.location='/item.view/'+i;
	return false;
}

function setprice(d1,d2) {
	var gi = findgrid(d1,d2,g);
	var sp = gi.saleprice;
	if(arguments.length > 2) {
		if($(arguments[2]).val() != '0') {
			sp = sp.replace(new RegExp(/^\W+/),"");
			sp = currencyformat(parseFloat(sp) + parseFloat(arguments[3]));
		}
	}
	$('#itemForm #gridid').val(gi.gridid);
	$("#sellPrice").html(sp);
}

function setcustomprice(d1,d2) {
	var gi = findgrid(d1,d2,cg);
	var sp = gi.saleprice;
	if(arguments.length > 8) {
		if($(arguments[2]).val() != '0') {
			sp = sp.replace(new RegExp(/^\W+/),"");
			sp = currencyformat(parseFloat(sp) + parseFloat(arguments[3]));
		}
	}
	$('#customform #gridid').val(gi.gridid);
	$("span.custom-price").html(sp);
}


function resetcustom(){
   	$("#platformType").attr('selectedIndex', 0);
   	$("#deviceType").html('<option value="'+'">Select Your Device</option>');
  	$("#deviceType").addClass('notyet');
	$('#deviceType').attr('disabled', 'disabled');
	$("#custom-step2").addClass('notyet');
	$("#custom-step3").addClass('notyet');
	$("#step2-content").html('');
	$("#custom-actions").hide();
	$("#standard-actions").hide();
	$("#arrow1").addClass('notyet');
	$("#arrow2").addClass('notyet');
}

function addcustomtocart(){
   $('#customform').submit();
}

function resetlaptops(){
	var obj = document.itemform;
	obj.buyqty = 1;
	obj.dim1[0].checked = true;
	obj.ref_width.value = '15';
	obj.ref_depth.value = '12';
	obj.dim2.selectedIndex = 0;
	$('#laptop-error').hide();
}

function resetnetbooks(){
	var obj = document.itemform;
	obj.buyqty = 1;
	obj.dim1[0].checked = true;
	obj.ref_width.value = '10';
	obj.ref_depth.value = '8';
	obj.dim2.selectedIndex = 0;
	$('#netbook-error').hide();
}

function checklaptopdata() {
	var err = '';
	var obj = document.itemform;
	if(obj.dim1[1].checked == true) {
		var wf = Math.floor(obj.ref_width.value);
		var wc = Math.ceil(obj.ref_width.value);
		var df = Math.floor(obj.ref_depth.value);
		var dc = Math.ceil(obj.ref_depth.value);
		
		if (!IsNumber(obj.ref_width.value)) {
			err = "Please enter a valid number for Width, with no more than 3 decimal places.";
		} else if (!IsNumber(obj.ref_depth.value)) {
			err = "Please enter a valid number for Depth, with no more than 3 decimal places.";
		} else if (!IsPositiveNumber(obj.buyqty.value)) { 
			err = "Please enter a valid purchase quantity to continue."; 
		} else if (wf > 16 || wc > 16) {
			err = "The maximum width for a laptop skin is 16 inches - for larger sizes, please contact customer service.";
		} else if (wf < 4 ) {
			err = "The minimum width for a laptop skin is 4 inches - for smaller sizes, please contact customer service.";
		} else if (df > 13 || dc > 13) {
			err = "The maximum depth for a laptop skin is 13 inches - for larger sizes, please contact customer service.";
		} else if (df < 4 ) {
			err = "The minimum depth for a laptop skin is 4 inches - for smaller sizes, please contact customer service.";
		} else {
			obj.reftext.value = "Width: " + obj.ref_width.value + "in, Depth: " + obj.ref_depth.value + "in";
		}
	} else {
		obj.reftext.value = "Width: 15in, Depth: 12in";
	}
		
	if(err != ''){
		$('#laptop-error').html(err);
		$('#laptop-error').fadeIn();
		return false;
	} else {
		$('#laptop-error').fadeOut();
		return true;
	}
}


function checknetbookdata() {
	var err = '';
	var obj = document.itemform;
	if(obj.dim1[1].checked == true) {
		var wf = Math.floor(obj.ref_width.value);
		var wc = Math.ceil(obj.ref_width.value);
		var df = Math.floor(obj.ref_depth.value);
		var dc = Math.ceil(obj.ref_depth.value);
		
		if (!IsNumber(obj.ref_width.value)) {
			err = "Please enter a valid number for Width, with no more than 3 decimal places.";
		} else if (!IsNumber(obj.ref_depth.value)) {
			err = "Please enter a valid number for Depth, with no more than 3 decimal places.";
		} else if (!IsPositiveNumber(obj.buyqty.value)) { 
			err = "Please enter a valid purchase quantity to continue."; 
		} else if (wf > 12 || wc > 12) {
			err = "The maximum width for a netbook skin is 12 inches - for larger sizes, please contact customer service.";
		} else if (wf < 5 ) {
			err = "The minimum width for a netbook skin is 5 inches - for smaller sizes, please contact customer service.";
		} else if (df > 10 || dc > 10) {
			err = "The maximum depth for a netbook skin is 10 inches - for larger sizes, please contact customer service.";
		} else if (df < 5 ) {
			err = "The minimum depth for a netbook skin is 5 inches - for smaller sizes, please contact customer service.";
		} else {
			obj.reftext.value = "Width: " + obj.ref_width.value + "in, Depth: " + obj.ref_depth.value + "in";
		}
	} else {
		obj.reftext.value = "Width: 10in, Depth: 8in";
	}
		
	if(err != ''){
		$('#netbook-error').html(err);
		$('#netbook-error').fadeIn();
		return false;
	} else {
		$('#netbook-error').fadeOut();
		return true;
	}
}

function setlaptopoptions(n) {
	if(n) {
		$('#laptop-options').attr('class', 'custom');
		$('#sellPrice').html('$24.99');
	} else {
		$('#laptop-options').attr('class', 'std');
		$('#sellPrice').html('$19.99');
	}
}

function setnetbookoptions(n) {
	if(n) {
		$('#netbook-options').attr('class', 'custom');
		$('#sellPrice').html('$17.99');
	} else {
		$('#netbook-options').attr('class', 'std');
		$('#sellPrice').html('$12.99');
	}
}



function currencyformat(c){
    var i = parseFloat(c);
	if(isNaN(i)) { i = 0.00; }
	var minus = '$';
	if(i < 0) { minus = '-$'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}

$(document).ready(function(){
	 var hidec = false;
	 $("#topnav li.cart, #hovercart").hover(function(){
		if (hidec) clearTimeout(hidec);
		if($("#cartCount").html() != '0') {
			if(cd == null) { fetchcart(); }
			$("#hovercart").fadeIn();
			$("#topnav li.cart").addClass('current');
		}
	 }, function() {
			 hidec = setTimeout(function() {
			 $("#hovercart").fadeOut("fast");
			 $("#topnav li.cart").removeClass('current');
		 }, 100);
	 }); 
	 $("a#login-link").click(function(e) { 
		e.preventDefault();  
		show_modal_login();
	});
	$('p.livehelp').click(function(){
		livehelp();							   
	});
	var hides = false;
	$("#topnav li.search, #hoversearch").hover(function(){
		if (hides) clearTimeout(hides);
		$("#hoversearch").fadeIn();
		$("#topnav li.search").addClass('current');
	}, function() {
			 hides = setTimeout(function() {
			 $("#hoversearch").fadeOut("fast");
			 $("#topnav li.search").removeClass('current');
		 }, 100);
	 }); 
	$('#overlay').click(function () {  
		hide_modal_window();
	});           
       
 }); 


function getDeliveryDateRange(startRange,endRange) {
	var monthNames = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
	var now = new Date();
	var startDate = new Date();
	var endDate = new Date();
	var dayOfTheWeek = now.getDay();
	var calendarDays1 = startRange;
	var calendarDays2 = endRange;
	var deliveryDay1 = dayOfTheWeek + startRange;
	var deliveryDay2 = dayOfTheWeek + endRange;
	if (deliveryDay1 >= 6) {
		startRange -= 6 - dayOfTheWeek;
		calendarDays1 += 2;
		deliveryWeeks = Math.floor(startRange / 5);
		calendarDays1 += deliveryWeeks * 2;
	}
	if (deliveryDay2 >= 6) {
		endRange -= 6 - dayOfTheWeek;
		calendarDays2 += 2;
		deliveryWeeks = Math.floor(endRange / 5);
		calendarDays2 += deliveryWeeks * 2;
	}
	startDate.setTime(now.getTime() + calendarDays1 * 24 * 60 * 60 * 1000);
	endDate.setTime(now.getTime() + calendarDays2 * 24 * 60 * 60 * 1000);
	//alert(properdate(startDate.getDate()));
 	return monthNames[startDate.getMonth()] + ' ' + properdate(startDate.getDate()) + ' - ' + monthNames[endDate.getMonth()] + ' ' + properdate(endDate.getDate());
}

function properdate(n) {
	var z = n.toString();
	z = z.charAt(z.length-1);
	if(n == '1') {
		return n + 'st';
	} else if (n == '2') {
		return n + 'nd';
	} else if (n == '3') {
		return n + 'rd';
	} else {
		return n + 'th';
	}
}

function currencyformat(c){
    var i = parseFloat(c);
	if(isNaN(i)) { i = 0.00; }
	var minus = '$';
	if(i < 0) { minus = '-$'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
};

function clearrecentsidebar() {
	$.getJSON("assets/ajax/decalgirl.cfc", { method: 'FlushRecent', returnformat : 'json', queryformat : 'column' }, function(j){ if(j.ROWCOUNT){ eval(j.DATA.CALLBACK[0]);} });
}

function fetchcart() {
	$.getJSON("assets/ajax/decalgirl.cfc", { method: 'GetCartData', returnformat : 'json', queryformat : 'column' }, function(j) {
		cd = j;
		drawhovercart();	
	});	
}
		
function hovercartnav(d) {
	hcs = hcs + d;
	if ((hcs>cd.ROWCOUNT) || (hcs==cd.rowcount)){
		hcs = 0;
	} else if (hcs < 0) {
		hcs = (Math.round(cd.ROWCOUNT/4)*4)-4;
	}
	drawhovercart()
}

function drawhovercart() {
	var h = '';
	var er = hcs + 4;
	if(cd.ROWCOUNT <=4 ) { $('#hovercart span.hccontrols').hide(); } else { $('#hovercart span.hccontrols').show(); }
	if(er > cd.ROWCOUNT) { er=cd.ROWCOUNT; } 
	$('#hovercart #counter').html('Items '+(hcs+1)+'-'+er+ ' of ' + cd.ROWCOUNT);
	for (var x=hcs; x<er;x++){
		//alert(cd.DATA.CARTID[x]);
		h = h+'<div id=\'hc' + cd.DATA.CARTID[x] + '\' class=\'tcrow clearfix\'>';
		h = h+'<a href=\'' + baseURL + 'item.view/'+cd.DATA.ITEMID[x]+'\'><img src=\'' + cd.DATA.PICTURE[x] + '\' /></a>';
		h = h+'<h3><a href=\'' + baseURL + 'item.view/'+cd.DATA.ITEMID[x]+'\'>'+ cd.DATA.NAME[x] + '</a></h3>';
		h = h+'<span class=\'prc\'>'+cd.DATA.ITEMQTY[x]+' @ '+ currencyformat(cd.DATA.UNITPRICE[x]) + '</span>';
		h = h+'</div>';
	}
	$('#tinycart').html(h);
	$("#tinycart div").click(function(){
		window.location = $(this).children("a").attr("href");
		return false;
	});
}


function search_execute() {
	$('##advsearchform').submit();	
}

function gallery_setstage(s) {
	$('span.artist-nav a').removeClass("chosen");
	switch(s.toLowerCase()) {
		case 'bio':
			$('a#a-bio').addClass("chosen");
			$('#artist-bio').show();
			$('#artist-designs').hide();
			$('#artist-discuss').hide();
			break;
		case 'discuss':
			$('a#a-discuss').addClass("chosen");
			$('#artist-bio').hide();
			$('#artist-designs').hide();
			$('#artist-discuss').show();
			break;
		default:
			$('a#a-designs').addClass("chosen");
			$('#artist-bio').hide();
			$('#artist-designs').show();
			$('#artist-discuss').hide();
			break;
	}
}

function showechohelp() {
	if ($('p.echo-intro').is(':visible')) {
		$('a#echohelp').html('?');
		$('p.echo-intro').hide();	
	} else {
		$('a#echohelp').html('X');
		$('p.echo-intro').show();	
	}
}

function macbookhelp(i) {
	$('#macbook-explained p').hide();
	$('#macbook-explained p#mb-'+i).show();
}