// JavaScript Document

// Declare variables
var browserName = navigator.appName,
	browserVer = parseInt(navigator.appVersion),
	$id = function(elem){return document.getElementById(elem);},
	$e = function(tag){return document.createElement(tag);},
	$text = function(text){return document.createTextNode(text);};

// Set up object for AJAX requests
var request = null;
try {
	request = new XMLHttpRequest();
} catch (trymicrosoft) {
	try {
		request = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (othermicrosoft) {
		try {
			request = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (failed) {
			request = null;
		}
	}
}

// Automatically tab to the specified field when the current field reaches a certain length
function autoTab(maxlength, field, next) {
	if (field.value.length >=  maxlength && next != null && next != undefined) next.select();
}

// Replaces node content with text
function replaceText(elem, newtext) {
	while (elem.firstChild != null) elem.removeChild(elem.firstChild);
	elem.appendChild(document.createTextNode(newtext));
}

// Gets the number of days in a month
function getDaysInMonth(aDate){
	// returns the last day of a given month
	var m = new Number(aDate.getMonth());
	var y = new Number(aDate.getYear());
	var tmpDate = new Date(y, m, 28);
	var checkMonth = tmpDate.getMonth();
	var lastDay = 27;
	while(lastDay <= 31){
		temp = tmpDate.setDate(lastDay + 1);
		if(checkMonth != tmpDate.getMonth()) break;
		lastDay++
	}
	return lastDay;
}

// Opens an eNews newsletter
function openNews(name) {
	var baseURL = '/newsletter/';
	if (document.location.protocol == "https:") baseURL = "http://" + location.host + baseURL;
	window.open(baseURL + name,'','scrollbars=yes,width=660,height=600,resizable=yes,status=yes');
}

function GetCookie (name) {
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	while (i < clen) {
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg)
		return getCookieVal(j);
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0) break; 
	}
	return null;
}

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" : "");
}

function FixCookieDate (date) {
	var base = new Date(0);
	var skew = base.getTime(); // dawn of (Unix) time - should be 0
	if (skew > 0)  // Except on the Mac - ahead of its time
		date.setTime (date.getTime() - skew);
}

function getCookieVal (offset) {
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1) endstr = document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}

// Validates the site search form
function validateSiteSearchForm(form) {
	if (form && form.st) {
		if (form.st.value.length > 0) return true;
		else {
			alert('Please enter a search term or phrase.');
			return false;
		}
	} else return false;
}

// Launch a demo popup
function launchDemo(name) {
	var baseURL = '';
	if (document.location.protocol == "https:") baseURL = "http://" + location.host;
	switch(name) {
		case "roes":
			window.open(baseURL + '/support/demos/resources/roes/loader.htm','','scrollbars=yes,width=700,height=525');
			break;
		case "labprints":
			location.href = '/support/demos/labprints/default.aspx';
			break;
		case "imagequix":
			window.open('http://www.imagequix.com/photog/1-020Demo.php','','scrollbars=yes,resizable=yes,menubar=yes,location=yes,toolbar=yes,status=yes,directories=yes');
			break;
		default:
			window.open(baseURL + '/support/demos/' + name + '.aspx','','scrollbars=yes,width=700,height=525');
			break;
	}
}

// Launch an OOS application
function launchApp(name) {
	var launch = false;
	var systemname = "";
	var account = GetCookie('CNU');
	if (account != '' && account != null && account != undefined) {
		switch(name) {
			case "fos":
				if (window.location.host == "customernet.fullcolor.com") window.location = "/onlineorderingsystem/jar/fullcolor.jnlp";
				else if (window.location.host == "www.fullcolor.com") window.location = "/onlineorderingsystem/jar/fullcolor.jnlp";
				else window.location = "/onlineorderingsystem/jar/dev.jnlp";
				systemname = "fos";
				break;
			case "eproofs":
				systemname = "EProofs";
				launch = true;
				break;
			case "imagenet":
				systemname = "ImageNet";
				launch = true;
				break;
			case "eventlink":
				systemname = "EventLink";
				launch = true;
				break;
			case "sportsnet":
				systemname = "SportsNet";
				launch = true;
				break;
			case "film2digital":
				systemname = "Film2Digital";
				launch = true;
				break;
		}
	} else alert('Please log in as a customer before launching this ordering system.');
	if (launch)	window.open('http://' + location.hostname + '/OnlineOrderingSystem/ASPX/Home.aspx?System=' + systemname + '&AccountNumber=' + account,'Home','top='+(screen.height-542)/2+',left='+(screen.width-786)/2+',status=no,scrollbars=no,resizable=yes,width=786,height=542')
}

// Shows a step-by-step DIV
function showItem(div) {
	var WinDiv = document.getElementById("Windows");
	var MacDiv = document.getElementById("Mac");
	switch(div) {
		case "Windows":
			if (WinDiv) WinDiv.style.display = '';
			if (MacDiv) MacDiv.style.display = 'none';
			break;
		case "Mac":
			if (WinDiv) WinDiv.style.display = 'none';
			if (MacDiv) MacDiv.style.display = '';
			break;
	}
}


// Image preloader script
function preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.p) d.p=new Array();
    var i,j=d.p.length,a=preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.p[j]=new Image; d.p[j++].src=a[i];}}
}


// Define all of the rollover button graphics
var buttonImages = new Array('add_as_new_item',
							 'add_card',
							 'add_new_card',
							 'add_to_shopping_cart',
							 'cancel',
							 'continue',
							 'delete',
							 'download_software',
							 'featured_next',
							 'featured_prev',
							 'edit',
							 'find',
							 'finish',
							 'go',
							 'go_back',
							 'launch_now',
							 'log_in',
							 'return_fix',
							 'send_message',
							 'sign_up_now',
							 'submit',
							 'submit_response',
							 'update',
							 'update_card',
							 'update_this_item');

// Sets up image rollovers
function setupButtons() {
	// Get all of the images on this page and iterate through them to determine if any are rollovers
	var pageImages = document.getElementsByTagName("img");
	for (var x = 0; x < pageImages.length; x++) {
		// Get the base name of the current image
		var tmparr1 = pageImages[x].src.split('/');
		var tmparr2 = tmparr1[tmparr1.length - 1].split('.');
		var imgname = tmparr2[0];
		// Check the current image name against the list of buttons and see if there is a match
		for (var i = 0; i < buttonImages.length; i++) {
			if (imgname == buttonImages[i]) {
				// Preload rollover image
				var normalURL = '/images/buttons/' + imgname + '.png';
				var rolloverURL = '/images/buttons/' + imgname + '_on.png';
				var hitURL = '/images/buttons/' + imgname + '_hit.png';
				// Setup rollover events
				addRollover(pageImages[x], normalURL, rolloverURL, hitURL);
				// Exit the loop
				break;
			}
		}
	}
	// Get all of the image buttons on this page and iterate through them to determine if any are rollovers
	var inputElements = document.getElementsByTagName("input");
	for (var x = 0; x < inputElements.length; x++) {
		if (inputElements[x].getAttribute("type") == "image") {
			// Get the base name of the current image
			var tmparr1 = inputElements[x].src.split('/');
			var tmparr2 = tmparr1[tmparr1.length - 1].split('.');
			var imgname = tmparr2[0];
			// Check the current image name against the list of rollovers and see if there is a match
			for (var i = 0; i < buttonImages.length; i++) {
				if (imgname == buttonImages[i]) {
					// Preload rollover image
					var normalURL = '/images/buttons/' + imgname + '.png';
					var rolloverURL = '/images/buttons/' + imgname + '_on.png';
					var hitURL = '/images/buttons/' + imgname + '_hit.png';
					// Setup rollover events
					addRollover(inputElements[x], normalURL, rolloverURL, hitURL);
					// Exit the loop
					break;
				}
			}
		}
	}
}

// Image button rollover/press handler handler
function addRollover(img, normalURL, rolloverURL, hitURL) {
	preloadImages(rolloverURL);
	//img.src = normalURL;
	img.onmouseover = function() { img.src = rolloverURL; }
	img.onmouseout = function() { img.src = normalURL; }
	if (hitURL.length > 0) {
		preloadImages(hitURL);
		img.onmousedown = function() { img.src = hitURL; }
		img.onmouseup = function() { img.src = rolloverURL; }
	}
}

// Function for enabling tab key usage (for textarea fields)
function setSelectionRange(input, selectionStart, selectionEnd) {
	if (input.setSelectionRange) {
		input.focus();
		input.setSelectionRange(selectionStart, selectionEnd);
	} else if (input.createTextRange) {
		var range = input.createTextRange();
		range.collapse(true);
		range.moveEnd('character', selectionEnd);
		range.moveStart('character', selectionStart);
		range.select();
	}
}
function replaceSelection (input, replaceString) {
	if (input.setSelectionRange) {
		var selectionStart = input.selectionStart;
		var selectionEnd = input.selectionEnd;
		input.value = input.value.substring(0, selectionStart)+ replaceString + input.value.substring(selectionEnd);
    	if (selectionStart != selectionEnd) setSelectionRange(input, selectionStart, selectionStart + replaceString.length);
		else setSelectionRange(input, selectionStart + replaceString.length, selectionStart + replaceString.length);
	} else if (document.selection) {
		var range = document.selection.createRange();
		if (range.parentElement() == input) {
			var isCollapsed = range.text == '';
			range.text = replaceString;
			if (!isCollapsed) {
				range.moveStart('character', -replaceString.length);
				range.select();
			}
		}
	}
}
// We are going to catch the TAB key so that we can use it, Hooray!
function catchTab(item,e){
	if (navigator.userAgent.match("Gecko")) c=e.which;
	else c=e.keyCode;
	if(c==9){
		replaceSelection(item,String.fromCharCode(9));
		setTimeout("document.getElementById('"+item.id+"').focus();",0);	
		return false;
	}
}

// Selects the first field of the login screen
function selectLoginField() {
	var form = document.getElementById("frmCNLoginMain");
	if (!form) form = document.getElementById("frmCNLoginPopup");
	if (form) form.txtUsername.select();
}

function DOMReady() {
	// Set up product catalog tabs
	$("#catalog-tabs").catalogTabs();
	$("#details, #specs").catalogSubTabs("sptb");
	$("#pnPricing").catalogSubTabs("prtb");
	$("#pnPromoPricing").catalogSubTabs("pptb");
	$("#images, #viewh, #viewv, #views").catalogImages();
	$("#ifviewswitcher").viewSwitcher();
	
	// Set up navigation menu
	var timer = null,
		hpstrip = document.getElementById("hpstrip");
		resetMenus = function() {
			clearTimeout(timer);
			$("#navmenu > a").removeClass('hover').each(function(){$("#"+this.id+"_subs").hide();});
			$("#navsubs > div").each(function(){$("#"+ this.id.replace("_subs", "")).removeClass('hover');$(this).hide();});
		};
	var toggleDropDowns = function(val) {
		if ($.browser.msie && /6.0/.test(navigator.userAgent) ) {
			if (val) $("select").css('visibility', ''); else $("select").css('visibility', 'hidden');
		}
	};
	$("#navmenu > a").each(function() {
		var subs = $("#" + this.id + "_subs"),
			main = $(this),
			showsub = (!hpstrip || this.id != "navmenu1");
		if (showsub) {
			main.mouseenter(function(){resetMenus();toggleDropDowns(false);main.addClass('hover');subs.show();});
			main.mouseleave(function(){timer=setTimeout(function(){resetMenus();toggleDropDowns(true);},400);});
		}
	});
	$("#navsubs > div").each(function() {
		var main = $("#" + this.id.replace("_subs", "")),
			subs = $(this);
		subs.mouseenter(function(){resetMenus();toggleDropDowns(false);main.addClass('hover');subs.show();});
		subs.mouseleave(function(){timer=setTimeout(function(){resetMenus();toggleDropDowns(true);},400);});
	});
	resetMenus();
	
	// Sets up image rollovers
	setupButtons();
	
	// Setup the CustomerNet login form
	$("#frmCNLoginPopup").bind('submit', function() {
		if (this.txtHCNUsername.value == '') {
			alert('Please enter your Account Number');
			return false;
		} else if (this.txtHCNPassword.value == '') {
			alert('Please enter your Password');
			return false;
		} else return true;
	});
	$("#frmCNLoginMain").bind('submit', function() {
		if (this.txtMCNUsername.value == '') {
			alert('Please enter your Account Number');
			return false;
		} else if (this.txtMCNPassword.value == '') {
			alert('Please enter your Password');
			return false;
		} else return true;
	});
	
	// Setup the site search form
	$("#frmSiteSearch").bind('submit', function() {
		if (this.st.value == '') {
			alert('Please enter a search term or phrase.');
			return false;
		} else return true;
	});
	
}

// jQuery extensions
(function ($) {
	// Getting QueryString parameters with $.qs()
    $.extend({
		qs: function(name) {
			function parseParams() {
				var params = {},
					e,
					a = /\+/g,  // Regex for replacing addition symbol with a space
					r = /([^&=]+)=?([^&]*)/g,
					d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
					q = window.location.search.substring(1);
                while (e = r.exec(q)) params[d(e[1])] = d(e[2]);
                return params;
			}
            if (!this.qsParams) this.qsParams = parseParams();
			return this.qsParams[name];
        }
    });
	
	$.extend($.fn, {
		// Catalog tabs
		catalogTabs: function() {
			$(this).each(function() {
				var obj = $(this), activeTab = location.hash, activeElem, tabElem, tabHash;
				if (!obj.children(":first").is("ul")) return;
				obj.hide();
				obj.children('div').not('div[id=' + activeTab.substr(1).replace('-', '\\-') + ']').each(function() {
					$(this).css('display', 'none');
				});
				obj.addClass('cattabs')
					.children('ul:first').addClass('cattabs_tabs').end()
					.children('div').addClass('cattabs_item').not('div[id=' + activeTab.substr(1).replace('-', '\\-') + ']').hide().end().end()
					.find('ul.cattabs_tabs a').each(function() {
						if (this.hash == activeTab) $(this).parent().addClass('active');
					}).click(function() {
						activeTab = this.hash;
						obj.find('ul.cattabs_tabs li').removeClass('active').end()
							.children('div')
								.not('div[id=' + activeTab.substr(1).replace('-', '\\-') + ']').hide().end()
								.filter('div[id=' + activeTab.substr(1).replace('-', '\\-') + ']').show();
						$(this).parent().addClass('active');
						$("#price-popup, #price-popupbkg").hide(); // Hide the pricing popup
						return false;
					}).prepend('<span/>');
				if (activeTab != "") activeElem = obj.children("#" + activeTab.substr(1).replace('-', '\\-') + ".cattabs_item");
				if (!activeElem || activeElem.length == 0) {
					tabElem = obj.find('ul.cattabs_tabs li:first');
					if (tabElem.length > 0) {
						tabHash = tabElem.children('a:first').attr('href');
						tabElem.addClass('active');
						obj.children('div[id=' + tabHash.substr(tabHash.indexOf("#")+1).replace('-', '\\-') + ']').show();
					}
				}
				obj.show();
			});
			$(window).load(function() {
				window.scrollTo(0, 0);
			});
		},
		
		// Catalog sub-tabs
		catalogSubTabs: function() {
			$(this).each(function() {
				var obj = $(this), qsparam = (arguments.length > 0) ? arguments[1] : "sub", activeTab = $.qs(qsparam), activeElem, tabElem, tabHash;
				if (!obj.children(":first").is("ul")) return;
				if (!activeTab) activeTab = "";
				obj.addClass('catsubtabs')
					.children('ul:first').addClass('catsubtabs_tabs').children('li:first').addClass('noborder').end().prepend('<li class="prefix">View:</li>').end()
					.children('div').addClass('catsubtabs_item').not('div[id=' + activeTab.replace('-', '\\-') + ']').hide().end().end()
					.find('ul.catsubtabs_tabs a').each(function() {
						if (this.hash.substr(1) == activeTab) $(this).addClass('active');
					}).click(function() {
						activeTab = this.hash.substr(1);
						obj.find('ul.catsubtabs_tabs a').removeClass('active').end()
							.children('div')
								.not('div[id=' + activeTab.replace('-', '\\-') + ']').hide().end()
								.filter('div[id=' + activeTab.replace('-', '\\-') + ']').show();
						$(this).addClass('active');
						$("#price-popup, #price-popupbkg").hide(); // Hide the pricing popup
						return false;
					});
				if (activeTab != "") activeElem = obj.children("#" + activeTab.replace('-', '\\-') + ".catsubtabs_item");
				if (!activeElem || activeElem.length == 0) {
					tabElem = obj.find('ul.catsubtabs_tabs a:first');
					if (tabElem.length > 0) {
						tabHash = tabElem.attr('href').substr(1);
						tabHash = tabHash.substr(tabHash.indexOf("#")+1);
						tabElem.addClass('active');
						obj.children('div[id=' + tabHash.replace('-', '\\-') + ']').show();
					}
				}
			});
		},
		
		// Iframe view switches
		viewSwitcher: function() {
			$(this).each(function() {
				var obj = $(this), qsparam = (arguments.length > 0) ? arguments[1] : "ifv", activeTab = $.qs(qsparam), activeElem, tabElem, tabHash;
				if (!activeTab) activeTab = "";
				obj.children('ul:first').addClass('ifnav').end()
					.children('div').addClass('ifswitch_item').not('div[id=' + activeTab.replace('-', '\\-') + ']').hide().end().end()
					.find('ul.ifnav li.orient1 a, ul.ifnav li.orient2 a').each(function() {
						if (this.hash.substr(1) == activeTab) $(this).addClass('active');
					}).click(function() {
						activeTab = this.hash.substr(1);
						obj.find('ul.ifnav a').removeClass('active').end()
							.children('div')
								.not('div[id=' + activeTab.replace('-', '\\-') + ']').hide().end()
								.filter('div[id=' + activeTab.replace('-', '\\-') + ']').show();
						$(this).addClass('active');
						return false;
					});
				if (activeTab != "") activeElem = obj.children("#" + activeTab.replace('-', '\\-') + ".ifswitch_item");
				if (!activeElem || activeElem.length == 0) {
					tabElem = obj.find('ul.ifnav li.orient1 a');
					if (tabElem.length > 0) {
						tabHash = tabElem.attr('href').substr(1);
						tabHash = tabHash.substr(tabHash.indexOf("#")+1);
						tabElem.addClass('active');
						obj.children('div[id=' + tabHash.replace('-', '\\-') + ']').show();
					} else obj.children('div:first').show();
				}
			});
		},
		
		// Catalog image views
		catalogImages: function() {
			$(this).each(function() {
				var obj = $(this), thumb, imgdiv, imgurl, swfurl, flashvars = {}, params = { wmode: "opaque" }, attributes = {};
				if (!obj.children(":first").is("ul")) return;
				imgdiv = obj.children('div').addClass('catviews_image');
				obj.addClass('catviews')
					.prepend('<span class="catviews_thumbshead">Product Views:</span>')
					.children('ul:first').addClass('catviews_thumbs')
						.children('li')
							.children('img').each(function() {
								// Preload each full-screen image
								(new Image()).src = this.src.replace('_thumb', '');
							}).end()
							.filter(':first').addClass('active').each(function() {
								thumb = $(this);
								imgurl = thumb.children('img:first').attr('src');
								imgdiv.removeAttr('title').css('background', 'none').empty();
								if (thumb.hasClass('view360')) {
									swfurl = thumb.attr('swfurl');
									imgdiv.attr('title', 'Click and drag to control rotation.').append('<div id="swf360"><p style="padding-top: 160px;"><b id="bNoFlash">This feature requires the Adobe Flash Plugin.</b></p></div>');
									swfobject.embedSWF(swfurl, "swf360", "617", "360", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
									imgdiv.append('<div class="swfoverlay">Click and drag to control rotation.</div>');
									/* It's the blink! $("#bNoFlash").each(function() {
										var elem = this;
										timer = setInterval(function() { elem.style.visibility = (elem.style.visibility == 'hidden') ? '' : 'hidden'; }, 1000);
									});*/
								} else {
									//clearInterval(timer);
									imgdiv.css('background', 'url(' + imgurl.replace('_thumb', '') + ') center center no-repeat');
								}
							}).end()
						.mouseenter(function() { $(this).addClass('hover'); })
						.mouseleave(function() { $(this).removeClass('hover'); })
						.click(function() {
							thumb = $(this);
							imgurl = thumb.children('img:first').attr('src');
							// Change the highlight
							thumb.addClass('active').siblings().removeClass('active');
							// Change the view
							imgdiv.removeAttr('title').css('background', 'none').empty();
							if (thumb.hasClass('view360')) {
								swfurl = thumb.attr('swfurl');
								imgdiv.attr('title', 'Click and drag to control rotation.').append('<div id="swf360"><p style="padding-top: 160px;"><b id="bNoFlash">This feature requires the Adobe Flash Plugin.</b></p></div>');
								swfobject.embedSWF(swfurl, "swf360", "617", "360", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
								imgdiv.append('<div class="swfoverlay">Click and drag to control rotation.</div>');
								/* It's the blink! $("#bNoFlash").each(function() {
									var elem = this;
									timer = setInterval(function() { elem.style.visibility = (elem.style.visibility == 'hidden') ? '' : 'hidden'; }, 1000);
								});*/
							} else {
								//clearInterval(timer);
								imgdiv.css('background', 'url(' + imgurl.replace('_thumb', '') + ') center center no-repeat');
							}
						}).end().end();
			});
		}
		
		
	});
})(jQuery);

// Fire DOM-ready event
$(function() { DOMReady() });
