global_relative_link_root = '';


var is_IE_Mac = false;
var is_IE_Win = false;

if(navigator.appName.indexOf("Microsoft") != -1 && navigator.platform.indexOf("Mac") != -1)
	is_IE_Mac = true;

if(navigator.appName.indexOf("Microsoft") != -1 && !is_IE_Mac)
	is_IE_Win = true;


window.addEvent('domready', function() {


	//this is for the multiBox (online tool)
	var initMultiBox = new multiBox({
		mbClass: '.mb',//class you need to add links that you want to trigger multiBox with (remember and update CSS files)
		container: $(document.body),//where to inject multiBox
		descClassName: 'multiBoxDesc',//the class name of the description divs
		path: './Files/',//path to mp3 and flv players
		useOverlay: true,//use a semi-transparent background. default: false;
		maxSize: {w:800, h:800},//max dimensions (width,height) - set to null to disable resizing
		addDownload: false,//do you want the files to be downloadable?
		pathToDownloadScript: 'Scripts/filedoesnotexist.txt',//if above is true, specify path to download script (php file)
		addRollover: true,//add rollover fade to each multibox link
		addOverlayIcon: true,//adds overlay icons to images within multibox links
		addChain: false,//cycle through all images fading them out then in
		recalcTop: true,//subtract the height of controls panel from top position
		addTips: true//adds MooTools built in 'Tips' class to each element (see: http://mootools.net/docs/Plugins/Tips)
	});

	
	//******************* Add/Remove from cart *********************************************
	
	var cartCheckboxElements = $$("input.cartCheckbox");
	cartCheckboxElements.addEvent("click", function(){
	
		currentCheckbox = this;
		
		var additional_values_array = new Array();
		var orid = '';
		var giftorid = '';
		var qty = 1;
		var display_right = false;
	
		if(currentCheckbox.type == 'button')
		{
			currentCheckbox.checked = true;
			currentValue = currentCheckbox.id;
			var display_right = true;
		}
		else
		{
			additional_values_array = currentCheckbox.name.split('|');
			currentCheckbox.value
			currentValue = currentCheckbox.value;
			if(additional_values_array[1] != null)
			{
				orid = additional_values_array[1];
			}
			if(additional_values_array[2] != null)
			{
				giftorid = additional_values_array[2];
				orid = giftorid;
			}
			if(additional_values_array[3] != null) //is prod
			{
				if($('pQuantity'+currentValue) != null)
					qty = $('pQuantity'+currentValue).value;
			}
		}
		
		if(currentCheckbox.checked)
			url_path = global_relative_link_root+'cart_addtocart/?sku='+currentValue+'&oid='+orid+'&qty='+qty;
		else
			url_path = global_relative_link_root+'cart_removefromcart/?sku='+currentValue;
		
		position = currentCheckbox.getPosition();
		

		var req = new Request.HTML({
	
			url:url_path, 
			onSuccess: function(html) {
				//Clear the text currently inside the results div.
				if($('cart_items') != null)
				{
					$('cart_items').set('text', '');
					$('cart_items').adopt(html);
				}
				else if(window.parent.$('cart_items') != null)
				{
					window.parent.$('cart_items').set('text', '');
					window.parent.$('cart_items').adopt(html);
					if(window.parent.$('productCheckbox'+currentValue) != null)
						window.parent.$('productCheckbox'+currentValue).checked = currentCheckbox.checked;
				}
				
								
				//************* show dialog box ********************************************
					//display the dialog box;
					$('dialogBox').set('text', '');
					//$('dialogBox').set('html', '<div style="background-color: #FFFFFF; padding: 5px;"><div id="dialogBoxDisplay" class="dialogBoxDisplay" style="padding-top:20px;padding-bottom:20px;" align="center"><img src="images/loading_bar.gif" width="220" height="19" /></div></div>'); //reset to the loading icon
					$('dialogBox').setStyle('opacity', 0);
					$('dialogBox').setStyle('visibility','visible');
					
					if(display_right)
						$('dialogBox').setStyle('left', position.x + 80);
					else
						$('dialogBox').setStyle('left', position.x - parseInt($('dialogBox').getStyle('width')));
					
					
					$('dialogBox').setStyle('top', position.y);
					
					$('dialogBox').set('morph', {link: 'chain'}); 
					$('dialogBox').morph({
						'opacity' : 1,
						'margin-top' : '-15px'
					});
					

					var reqcart = new Request.HTML({
		
						url:global_relative_link_root+'cart_response/?sku='+currentValue,
						onSuccess: function(html) {
							//Inject the new DOM elements into the results div.
							$('dialogBox').set('text', '');
							$('dialogBox').adopt(html);
							//this is just to add extra time
							$('dialogBox').morph({
								'opacity' : 1
							});
							$('dialogBox').morph({
								'opacity' : 1
							});
							$('dialogBox').morph({
								'opacity' : 0,
								'margin-top' : 0
							});
							
							if($('cartTotalsArea') != null)
							{
								//if(qty)
									//update_orderline_item_total(currentValue, 0);
								//else
								//{
									url_path = 'cart_viewtotals/?';
									update_cart_totals(url_path);
								//}
							}
							
						},
						
						onFailure: function() {
							$('dialogBox').set('text', '?');
						}
					});
					
					//alert(currentCheckbox.title);
					
					if(giftorid)
					{
						update_orderline_gift_item_total(currentValue, giftorid);
					}
					
					reqcart.send();
					
				//************* END show dialog box ********************************************
				
			},
			//Our request will most likely succeed, but just in case, we'll add an
			//onFailure method which will let the user know what happened.
			onFailure: function() {
				//$('cart_items').set('text', '?');
			}
		});
		
		req.send();
		
		
		
		
		
		
	});
	
	
	//******************* Add/Remove from wishlist *********************************************
	
	var wishlistElements = $$(".wishlistItem");
	wishlistElements.addEvent("click", function(e){
		
		selectedElement = this;
		position = selectedElement.getPosition();
		//url_path = selectedElement.href;
		url_path = global_relative_link_root+'cart_wishlist/?wishsku='+selectedElement.value;
		//e.stop();
		
		currentValue = selectedElement.value;
		
		var reqwishlist = new Request.HTML({
	
			url:url_path, 
			onSuccess: function(html) {
			
				if(window.parent.$('wishlistCheckbox'+currentValue) != null)
					window.parent.$('wishlistCheckbox'+currentValue).checked = selectedElement.checked;
				
				/*
				if(selectedElement.rel == 1)
				{
					selectedElement.rel = 0;
					selectedElement.set('text', 'remove from Wish List');
				}
				else
				{
					selectedElement.rel = 1;
					selectedElement.set('text', 'add to Wish List');
				}
				*/
				
				//************* show dialog box ********************************************
					//display the dialog box;
					$('dialogBox').set('text', '');
					$('dialogBox').adopt(html);
					$('dialogBox').setStyle('opacity', 0);
					$('dialogBox').setStyle('visibility','visible');
					
					$('dialogBox').setStyle('left', position.x - parseInt($('dialogBox').getStyle('width')));
					$('dialogBox').setStyle('top', position.y);
					
					$('dialogBox').set('morph', {link: 'chain'}); 
					$('dialogBox').morph({
						'opacity' : 1,
						'margin-top' : '-15px'
					});
					$('dialogBox').morph({
						'opacity' : 1
					});
					$('dialogBox').morph({
						'opacity' : 1
					});
					$('dialogBox').morph({
						'opacity' : 0,
						'margin-top' : 0
					});					
				//************* END show dialog box ********************************************
				
			},

			onFailure: function() {
				//$('cart_items').set('text', '?');
				alert('FAILED');
			}
		});
		
		reqwishlist.send();
	
	});
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	var prodTypeImage = $$(".prodTypeIcon");
	prodTypeImage.addEvent("mouseenter", function(){
		this.set('tween',{duration:200,transition:Fx.Transitions.linear}).tween('opacity',0.5);
		
		group = this.get('rel');
		currentElement = this;
		
		$('dialogBox').set('text', '');
		$('dialogBox').setStyle('opacity', 0);
		$('dialogBox').setStyle('visibility','visible');
		
		$('dialogBox').setStyle('left', currentElement.getPosition().x + parseInt(currentElement.getStyle('width')));
		$('dialogBox').setStyle('top', currentElement.getPosition().y + parseInt(currentElement.getStyle('height')));
		$('dialogBox').morph({
			'opacity' : 1,
			'margin-top' : '-15px'
		});

		var reqdialog = new Request.HTML({		
			url:global_relative_link_root+'prod_types.php?type='+group,
			onSuccess: function(html) {
				$('dialogBox').adopt(html);
			},
			
			onFailure: function() {
				$('dialogBox').set('text', '?');
			}
		});
		
		reqdialog.send();
		
	});
	prodTypeImage.addEvent("mouseleave", function(){
		this.set('tween',{duration:400,transition:Fx.Transitions.linear}).tween('opacity',1);
		$('dialogBox').morph({
			'opacity' : 0,
			'margin-top' : 0
		});
	});
	
	
	
	var sampleDisplay = $$(".sampleDisplay");
	sampleDisplay.addEvent("mouseenter", function(){
		this.set('tween',{duration:200,transition:Fx.Transitions.linear}).tween('opacity',0.5);
		
		productid = this.get('rel');
		currentElement = this;
		
		$('dialogBox').set('text', '');
		$('dialogBox').setStyle('opacity', 0);
		$('dialogBox').setStyle('visibility','visible');
		
		$('dialogBox').setStyle('left', currentElement.getPosition().x + parseInt(currentElement.getStyle('width')));
		$('dialogBox').setStyle('top', currentElement.getPosition().y + parseInt(currentElement.getStyle('height')));
		$('dialogBox').morph({
			'opacity' : 1,
			'margin-top' : '20px'
		});

		var reqdialog = new Request.HTML({		
			url:global_relative_link_root+'prod_sample_display.php?pid='+productid,
			onSuccess: function(html) {
				$('dialogBox').adopt(html);
			},
			
			onFailure: function() {
				$('dialogBox').set('text', '?');
			}
		});
		
		reqdialog.send();
		
	});
	sampleDisplay.addEvent("mouseleave", function(){
		this.set('tween',{duration:400,transition:Fx.Transitions.linear}).tween('opacity',1);
		$('dialogBox').morph({
			'opacity' : 0,
			'margin-top' : '40px'
		});
	});
	
	
	
	//************************ This is for navigation tabs **************
		settings = {
		  tl: { radius: 5 },
		  tr: { radius: 5 },
		  bl: { radius: 0 },
		  br: { radius: 0 },
		  antiAlias: true,
		  autoPad: true,
		  validTags: ["div"]
		}
		
		var pageTabsObject = new curvyCorners(settings, "pageTabs");
		pageTabsObject.applyCornersToAll();
		var pageTabsObject = new curvyCorners(settings, "pageTabsSelected");
		pageTabsObject.applyCornersToAll();
	//************************ END This is for navigation tabs **************
	
	
});


function update_cart_totals(url_path)
{
	var cartTotals = new Request({
		
		url:global_relative_link_root+url_path,
		onSuccess: function(paramlist) {
			//Inject the new DOM elements into the results div.
			var cart_totals_array = new Array();
			cart_totals_array = paramlist.split('|');
			
			$('cartTotalsArea_subtotal').set('text', '$'+parseFloat(cart_totals_array[0]).toFixed(2));
			$('cartTotalsArea_transfee').set('text', '$'+parseFloat(cart_totals_array[1]).toFixed(2));
			$('cartTotalsArea_shipfee').set('text', '$'+parseFloat(cart_totals_array[2]).toFixed(2));
			$('cartTotalsArea_discount').set('text', '$'+parseFloat(cart_totals_array[3]).toFixed(2));
			$('cartTotalsArea_salestax').set('text', '$'+parseFloat(cart_totals_array[4]).toFixed(2));
			$('cartTotalsArea_total').set('text', '$'+parseFloat(cart_totals_array[5]).toFixed(2));
		},
		
		onFailure: function() {
			$('cartTotalsArea').set('text', 'The cart totals cannot be displayed.');
		}
	});
	
	cartTotals.send();
}


function custom_cd_selection()
{
	var custom_cd = '';
	var url_path = '';
	
	if(document.getElementById('custom_cd').checked)
		custom_cd = 1;
	
	url_path = 'cart_additionalitems/?cop='+custom_cd+'&rid='+Math.floor((Math.random()*1000001));
	update_cart_totals(url_path);	
	
}


function additional_items_selection()
{		
	var custom_cd = '';
	var additional_item = '';
	var url_path = '';
		
	if(document.getElementById('custom_cd').checked)
		custom_cd = 1;
	
	if(document.getElementById('additional_item')!=null)
	{
		if(document.getElementById('additional_item').checked)
			additional_item = 1;
	}
		
	url_path = 'cart_additionalitems/?cop='+custom_cd+'&add1='+additional_item+'&rid='+Math.floor((Math.random()*1000001));
	update_cart_totals(url_path);
	
}


function update_orderline_item_total(currentSKU, orderlineID)
{
	var orderlineItemTotal;
	var priceEach;
	var priceAdditional;
	var pQuantity = 1;
	 
	if(orderlineID > 0 && document.getElementById('multiunit'+orderlineID).value == 1)
	{
		
		if(document.getElementById('productCheckbox'+currentSKU).checked)
		{
			document.getElementById('unitqty'+orderlineID).value = parseInt(document.getElementById('unitqty'+orderlineID).value) + 1;
		}
		else
		{
			document.getElementById('unitqty'+orderlineID).value = parseInt(document.getElementById('unitqty'+orderlineID).value) - 1;
		}
		
		var SKU = currentSKU.split(".");
		var currentSKU = SKU[0];
		
		priceEach = parseInt(document.getElementById("unitpricefirst"+orderlineID).value);
		priceAdditional = parseInt(document.getElementById("unitpriceadd"+orderlineID).value);
		
		if(parseInt(document.getElementById("unitqty"+orderlineID).value) > 0)
		{
			pQuantity = parseInt(document.getElementById("unitqty"+orderlineID).value) - 1;
			orderlineItemTotal = pQuantity  * priceAdditional + priceEach;
		}
		else 
		{
			orderlineItemTotal = 0;
		}
		
		document.getElementById('orderline_item_total'+currentSKU).innerHTML = '$'+orderlineItemTotal.toFixed(2);
		document.getElementById('orderline_item_price'+currentSKU).innerHTML = '$'+orderlineItemTotal.toFixed(2);
		
	}
	else 
	{
		if(document.getElementById('productCheckbox'+currentSKU).checked)
		{
			if(document.getElementById('pQuantity'+currentSKU).value > 1)
				pQuantity = parseInt(document.getElementById('pQuantity'+currentSKU).value);
			else
				document.getElementById('pQuantity'+currentSKU).value = 1;
		
			priceEach = document.getElementById("priceEach"+currentSKU).value;
			orderlineItemTotal = pQuantity * priceEach;
			document.getElementById('orderline_item_total'+currentSKU).innerHTML = '$'+orderlineItemTotal.toFixed(2);
		
			if(orderlineID > 0)
			{
				url_path = 'cart_viewtotals/?qty='+pQuantity+'&olid='+orderlineID+'&rid='+Math.floor((Math.random()*1000001));
				update_cart_totals(url_path);
			}
		}
		else
		{
			orderlineItemTotal = 0;
			document.getElementById('orderline_item_total'+currentSKU).innerHTML = '$'+orderlineItemTotal.toFixed(2);
		}
	}
}


function update_orderline_gift_item_total(currentSKU, orderlineID)
{
	pPrice = parseFloat(document.getElementById('pPrice'+orderlineID).value);
	if(pPrice > 0)
	{
		//valid may need to check for max values here
		if(pPrice > 200)
		{
			pPrice = 200;
			document.getElementById('pPrice'+orderlineID).value = pPrice;
		}	
	}
	else
	{
		pPrice = 0;
		document.getElementById('pPrice'+orderlineID).value = pPrice;
	}
	url_path = 'cart_viewtotals_gift/?price='+pPrice+'&olid='+orderlineID+'&rid='+Math.floor((Math.random()*1000001));
	update_cart_totals(url_path);
	
}

function clear_seach_form_params()
{
	var clear_elements_array = new Array(	'catid',
											'subcatid',
											'showonly',
											'sampsize',
											'showrelated',
											'sku',
											'maker',
											'designer',
											'mylib',
											'libfree',
											'days',
											'prodline',
											'trait',
											'sale_price');
	
	
	
	for(i=0; i<clear_elements_array.length; i++)
	{
		if(document.getElementById(clear_elements_array[i]) != null)
		{
			document.getElementById(clear_elements_array[i]).value = '';
		}
	}
	
	if(document.getElementById('showingonly') != null)
		document.getElementById('showingonly').selectedIndex=0;
	
	if(document.getElementById('filter') != null)
		document.getElementById('filter').selectedIndex=0;
	
	if(document.getElementById('page') != null)
		document.getElementById('page').selectedIndex=0;
	
	if(document.getElementById('page_bm') != null)
		document.getElementById('page_bm').selectedIndex=0;
}

function toggleSection(section_id)
{
	var myVerticalSlide = new Fx.Slide(section_id);
	myVerticalSlide.toggle();
}

function hideSection(section_id)
{
	var myVerticalSlide = new Fx.Slide(section_id);
	myVerticalSlide.hide();
}

function showSection(section_id)
{
	var myVerticalSlide = new Fx.Slide(section_id);
	myVerticalSlide.show();
}

function isValidEmail(value)
{
	var x = value;
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (filter.test(x)) return true;
	else return false;
}

function isValidPhoneNumber(s)
{
	// Check for correct phone number
	rePhoneNumber = new RegExp(/^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/);
	
	if (!rePhoneNumber.test(s))
		return false;
	
	return true;
}

function formValidate(formobj){
	// Enter name of mandatory fields
	//var fieldRequired = Array("FirstName","First Name","email","LastName","Last Name","ssn");
	//You can have as many required arrays as desired i.e. formValidate(formobj, Array1, Array2,...)
	
	var backgroundColorFail = "#FF9999";
	var backgroundColorVaild = "#FFFFFF";
	
	// dialog message
	var alertMsg = "Please complete the following fields:\n";
	
	var l_Msg = alertMsg.length;
	
	args=formValidate.arguments;
	
	for (var k = 1; k < args.length; k++)
	{	
		var fieldRequired = args[k];
		for (var i = 0; i < fieldRequired.length; i++)
		{
			var obj = formobj.elements[fieldRequired[i]];
			if (obj){
				switch(obj.type){
				case "select-one":
					if (obj.selectedIndex == -1 || obj.options[obj.selectedIndex].text == ""){
						alertMsg += " - " + fieldRequired[i+1] + "\n";
						obj.style.background = backgroundColorFail;
					}
					else
						obj.style.background = backgroundColorVaild;
					break;
				case "select-multiple":
					if (obj.selectedIndex == -1){
						alertMsg += " - " + fieldRequired[i+1] + "\n";
						obj.style.background = backgroundColorFail;
					}
					else
						obj.style.background = backgroundColorVaild;
					break;
				case "text":
				case "textarea":
				case "password":
					if (obj.value == "" || obj.value == null)
					{
						alertMsg += " - " + fieldRequired[i+1] + "\n";
						obj.style.background = backgroundColorFail;
					}
					else if(fieldRequired[i+2] == 'email')
					{
						if(!isValidEmail(obj.value))
						{
							alertMsg += " - " + fieldRequired[i+1] + " must be an email address\n";
							obj.style.background = backgroundColorFail;	
						}
						else
							obj.style.background = backgroundColorVaild;
					}
					else if(fieldRequired[i+2] == 'phone')
					{
						if(!isValidPhoneNumber(obj.value))
						{
							alertMsg += " - " + fieldRequired[i+1] + " must be entered as: (555) 555-1234\n";
							obj.style.background = backgroundColorFail;	
						}
						else
							obj.style.background = backgroundColorVaild;
					}
					else if(fieldRequired[i+2] == 'date')
					{
						if(!validateDate(obj.value,'U','A'))
						{
							alertMsg += " - " + fieldRequired[i+1] + " must be a date formatted mm-dd-yyyy\n";
							obj.style.background = backgroundColorFail;	
						}
						else
							obj.style.background = backgroundColorVaild;
					}
					else
						obj.style.background = backgroundColorVaild;
					break;
				default:
				}
				if (obj.type == undefined){
					var blnchecked = false;
					for (var j = 0; j < obj.length; j++){
						if (obj[j].checked){
							blnchecked = true;
						}
					}
					if (!blnchecked)
					{
						alertMsg += " - " + fieldRequired[i+1] + "\n";
					}
				}
			}
			
			i=i+2;
		}
	}

	if (alertMsg.length == l_Msg){
		return true;
	}else{
		if(alertMsg.length > 100)
			alertMsg = '(Press "ENTER" on your keybord to continue.)\n'+alertMsg;
		alert(alertMsg);
		return false;
	}
}

function verifyPassword(form_element)
{
	var errors = '';
	
	if(form_element.password.value.length < 4)
  		errors += '- Your password needs to be at least four characters.\n';
  
 	if(form_element.password.value != form_element.password_confirm.value)
  		errors += '- Your password does not match the password confirm.\n';
	
	if(form_element.terms.value != null && !form_element.terms.checked)
  		errors += '- You must agree to the terms of use.\n';
	
	if(errors)
	{
		alert('The following error(s) occurred:\n'+errors);
		return false;
	}
	else
		return true;
	
}

function roundNumber(rnum, rlength) { // Arguments: number to round, number of decimal places
	return Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
}
