// JavaScript Document

//GLOBALS
/*
*
* LEAVE THESES ALONE
*
*/
//FOR CONFIRM FUNCTION
var confirmed = false;
var elementClass = '';
var titleText = '';


// confirmAction()
/*
* Builds arrays where confirmation can take place
*
* @return bool
*/
function confirmAction() {

	//IS DOM SUPPORTED
	if(!document.getElementsByTagName('a')) return false;

	//GET ELEMENTS ON PAGE TO WORK WITH
	var confirmLinks   = document.getElementsByTagName('a');
	var buttons = document.getElementsByTagName('input');
	
	//PROCESS ELEMENTS
	loopElements(confirmLinks);
	loopElements(buttons);
	
	return false;

}

// loopElements()
/*
* Processes passed elements, gets text for confirm box and sends for confirmation
* @return bool @param array of elements
*/
function loopElements(elements) {
	
	for(var i=0; i<elements.length; i++) { //LOOP THROUGH ELEMENTS
	
		elementClass = elements[i].className; //ASSIGN CLASSNAME
		
		if(elementClass != '' && elementClass.indexOf('confirm') > -1) { //DOES CONFIRM CLASSNAME EXIST ON ELEMENT
		
			elements[i].onclick = function() { //ELEMENT CLICKED
			
				titleText = '';
			
				if(this.getAttribute('alt')) {
					
					titleText = this.getAttribute('alt'); //GET TEXT FROM ALT ATTRIBUTE ON BUTTONS
					
				}else if(this.getAttribute('title')) {
					
					titleText = this.getAttribute('title');	//GET TEXT FROM TITLE ON LINKS
					
				}
				
				if(titleText.length > 0) alertText = titleText; //APPLY TEXT TO VARIABLE
				
				confirmed = getConfirmation(alertText); //PASS TEXT TO FUNCTION
				
				return confirmed; //RETURN RESULT
			
			}
		
		}
	
	}
	
}

// getConfirmation()
/*
* Displays confirmation box returns result
* @return bool @param String of text to display
*/
function getConfirmation(text) {

	var result = confirm(text); //SHOW CONFIRMATION BOX

	return result; //RETURN RESULT

}

// externalLinks()
/*
* Allows external links to be opened in a new window without the use of target attribute
* @return bool
*/
function externalLinks() {
	
	//SETS DOMAIN OF SITE
	var domainName=document.domain;
	
	var externalLinks=document.getElementsByTagName("a"); //FIND ALL LINKS ON THE CURRENT PAGE
	
	for(var i=0; i<externalLinks.length; i++) { //LOOP THROUGH LINKS ARRAY
	
		var attribute=externalLinks[i].getAttribute("href"); //GETS CONTENT OF 'HREF' ATTRIBUTE ON CLICKED LINK
		
		var elementClass = externalLinks[i].className; //STORES CLASS NAME OF ELEMENT
		
		var contains_http=attribute.indexOf("http"); //GET VALUE http IN 'HREF' **FOR MOZILLA&&
		
		var contains_domain=attribute.indexOf(domainName); //GET VALUE domainName **FOR IE**
		
		if(newWindowLink == true) {
		
			if(contains_http>-1 && contains_domain==-1) { //DOES CONTAIN AN 'http' OR DOES NOT CONTAIN domainName
			
				setElementAttribute(externalLinks[i], 'target', '_blank');	
				
			}
		
		}
		
		if(elementClass.indexOf('new_window') > -1 ) { //FORCE LINK TO OPEN IN NEW WINDOW
			
			setElementAttribute(externalLinks[i], 'target', '_blank');
			
		}
		
	}
	
}

// setElementAttribute()
/*
* Sets elements attribute
* @return bool; @param element: Element to attach attr to, attr: The attribute to be added, val: value of attribute
*/
function setElementAttribute(element, attr, val) {

	element.setAttribute(attr, val); //SET ATTRIBUTE ON ELEMENT

	return true;

}

// popUpWindows()
/*
* Creates a popup window
* @return bool;
*/
function popUpWindows() {
	
	var links = document.getElementsByTagName('a'); //MAKE ARRAY OF LINKS
	var url = '';
	
	for(var i=0; i<links.length; i++) { //LOOP LINKS
		
		var classes = links[i].className;
		
		if(classes != '') {
			
			var splitClasses = classes.split(' '); //EXPLODE CLASSES ON SPACE ' '
					
			for(var x=0; x<splitClasses.length; x++) { //LOOP THROUGH MULTIPLE CLASSNAMES
					
				if(splitClasses[x].indexOf('popup_window') > -1) { //IS LINK A POPUP WINDOW
				
					links[i].onclick = function() { //LINK CLICKED
			
						var classes = this.className; //GET CLASS NAMES
					
					
						
						url = this.getAttribute('href'); //FINDS WHAT PAGE WINDOW IS TO SHOW
								
						var dimentions = getDimentions(splitClasses[x]); //GET DIMENTIONS
								
						var newWindow = window.open(url, '', 'width='+dimentions['width']+', height='+dimentions['height']+', scrollbars=yes, resize=yes'); //SET NEW WINDOW
								
						newWindow; //LAUNCH
								
						return false; //STOP LINK
							
					}
						
				}
				
			}
		
		}
	
	}
	
}

// getDimentions()
/*
* Gets dimentions of popup window
* @return array; @param thisClass: Classname of link clicked
*/
function getDimentions(thisClass) {

	var parts = thisClass.split('_'); //EXPLODE CLASSNAME ON UNDERSCORE _
	var winWidth = parts[parts.length-2]; //WIDTH IS SECOND LAST ELEMENT
	var winHeight = parts[parts.length-1]; //HEIGHT IS LAST ELEMENT
	
	var dimentions = new Array();
	
	dimentions['width']  = winWidth;
	dimentions['height'] = winHeight;
	
	return dimentions; //RETURN

}


// EDIT THESE VALUES IF REQUIRED
var alertText = 'Are you sure you wish to perform this action' + "\n"; //DEFAULT TEXT DISPLAYED ON CONFIRM BUTTONS/LINKS WHEN NO ALT/TITLE
var newWindowLink = false; //OPEN EXTERNAL LINKS BY DEFAULT IN A NEW WINDOW (TRUE/FALSE)?


var woms = new Array(); //CREATE ARRAY OF FUNCTIONS TO LAUNCH ONLOAD

//ONLOAD MANAGER
function womOn(){
  window.onload = womGo;
}

function womGo(){
  for(var i = 0;i < woms.length;i++)
    eval(woms[i]);
}

function womAdd(func){
  woms[woms.length] = func;
}



function CreateBookmarkLink() {

	title = document.title;
	url = window.location.href;
	
	if (window.sidebar) { 
		window.sidebar.addPanel(title, url,"");
	} else if(window.external) {
		window.external.AddFavorite( url, title); 
	} else if(window.opera && window.print) {
		return true;
	}
	
}

function objToggle(obj) { 

	var obj = document.getElementById(obj);

	if(obj.style.display == "block") { 
		obj.style.display = "none";
	} else { 
		obj.style.display = "block";
	}

}

function objToggleMenu(obj, cat_id) { 

	var obj = document.getElementById(obj);
	var arrow = 'arrow_' + cat_id;
	
	if(obj.style.display == "block") { 
		obj.style.display = "none";
		document.getElementById(arrow).src = 'images/arrow_down.gif';
	} else { 
		obj.style.display = "block";
		document.getElementById(arrow).src = 'images/arrow_up.gif';
	}

}


function showFabricBoxes(location){
	
	var div = document.getElementById(location);
	var ulList = div.getElementsByTagName('ul');
	
	for(var i=0; i<ulList.length; i++) {
		
		var liList = ulList[i].getElementsByTagName('li');
		
		for (var x=0; x<liList.length; x++){
			
			if (x > 15){
				
				if (liList[x].style.display == 'block') liList[x].style.display = 'none';
				if (liList[x].style.display == 'none') liList[x].style.display = 'block';
				
			}
			
		}
		
	}
	
	document.getElementById('fabric_expander').innerHTML = '';
	
	return true;
	
}



function imageSwap() {

	if(!document.getElementById('thumb_list')) return false;

	var placeHolder  = document.getElementById('main'); //LARGE IMAGE
	var imageList    = document.getElementById('thumb_list'); //UL OF IMAGE LIST
	var listElements = imageList.getElementsByTagName('li'); //LIS IN IMAGELIST
	var ahref		 = document.getElementById('ahref');
	
	for(var i=0; i<listElements.length; i++) { //LOOP THROUGH LIS
	
		var image = listElements[i].getElementsByTagName('img'); //GET IMAGES WITHIN LIS
		
		for(var x=0; x<image.length; x++) { //LOOP IMAGES
		
			image[x].onclick = function() { //CLICKED ON AN IMAGE
			
				//THUMB FILENAME
				var file_location = this.getAttribute('src'); //GET FILE LOCATION
				var location_explode = file_location.split('/');
				var filename = location_explode[(location_explode.length-1)]; //FIND LAST VALUE
				
				//CURRENT LARGE FILENAME
				var file_location = placeHolder.getAttribute('src');
				var location_explode = file_location.split('/');
				var large_filename = location_explode[(location_explode.length-1)]; //FIND LAST VALUE
				
				var thumb = 'uploads/images/products/tinythumbs/'+large_filename; //SET NEW SRC FOR THUMBNAME
				var large = 'uploads/images/products/large/'+filename; //SET NEW SRC FOR PLACEHOLDER
				var enlargement = 'uploads/images/products/huge/'+filename;
				
				placeHolder.setAttribute('src', large); //SET ATTS
				ahref.setAttribute('href', enlargement);
				this.setAttribute('src', thumb);
			
			}
		
		}
		
	
	}
	
}

function prodAdminToggle(obj) { 
	
	if (obj == 'general'){
		document.getElementById('general').style.display = "block";			
		document.getElementById('location').style.display = "none";	
		document.getElementById('associated').style.display = "none";
		document.getElementById('amazon').style.display = "none";
		document.getElementById('promo').style.display = "none";
		document.getElementById('fabrics').style.display = "none";
		document.getElementById('image').style.display = "none";
		document.getElementById('tab').value = 'general';
	}
	
	if (obj == 'location'){
		document.getElementById('general').style.display = "none";	
		document.getElementById('location').style.display = "block";
		document.getElementById('associated').style.display = "none";	
		document.getElementById('amazon').style.display = "none";
		document.getElementById('promo').style.display = "none";
		document.getElementById('fabrics').style.display = "none";
		document.getElementById('image').style.display = "none";
		document.getElementById('tab').value = 'location';
	}
	
	if (obj == 'associated'){
		document.getElementById('general').style.display = "none";			
		document.getElementById('location').style.display = "none";	
		document.getElementById('associated').style.display = "block";
		document.getElementById('amazon').style.display = "none";
		document.getElementById('promo').style.display = "none";
		document.getElementById('fabrics').style.display = "none";
		document.getElementById('image').style.display = "none";
		document.getElementById('tab').value = 'associated';
	}
	
	if (obj == 'amazon'){
		document.getElementById('general').style.display = "none";			
		document.getElementById('location').style.display = "none";	
		document.getElementById('associated').style.display = "none";
		document.getElementById('amazon').style.display = "block";
		document.getElementById('promo').style.display = "none";
		document.getElementById('fabrics').style.display = "none";
		document.getElementById('image').style.display = "none";
		document.getElementById('tab').value = 'amazon';
	}

	if (obj == 'promo'){
		document.getElementById('general').style.display = "none";			
		document.getElementById('location').style.display = "none";	
		document.getElementById('associated').style.display = "none";
		document.getElementById('amazon').style.display = "none";
		document.getElementById('promo').style.display = "block";
		document.getElementById('fabrics').style.display = "none";
		document.getElementById('image').style.display = "none";
		document.getElementById('tab').value = 'promo';
	}
	
	if (obj == 'fabrics'){
		document.getElementById('general').style.display = "none";			
		document.getElementById('location').style.display = "none";	
		document.getElementById('associated').style.display = "none";
		document.getElementById('amazon').style.display = "none";
		document.getElementById('promo').style.display = "none";
		document.getElementById('fabrics').style.display = "block";
		document.getElementById('image').style.display = "none";
		document.getElementById('tab').value = 'fabrics';
	}
	
	if (obj == 'image'){
		document.getElementById('general').style.display = "none";			
		document.getElementById('location').style.display = "none";
		document.getElementById('associated').style.display = "none";	
		document.getElementById('amazon').style.display = "none";
		document.getElementById('promo').style.display = "none";
		document.getElementById('fabrics').style.display = "none";
		document.getElementById('image').style.display = "block";
		document.getElementById('tab').value = 'image';
	}
	
}


function validate(formobj, formtype){
		
	switch(formtype) { 
		case "contact":
			var fieldRequired = Array("enq_name", "enq_email", "enq_telephone", "enq_referral", "enq_comments");
			break;
		case "register":
			var fieldRequired = Array("account_username", "account_password", "account_confirm_password", "account_fullname", "account_email", "account_company", "account_outlet");
			break;
		case "checkout":
			var fieldRequired = Array("order_del_name", "order_del_addr1", "order_del_postcode", "order_del_tel", "order_bil_name", "order_bil_addr1", "order_bil_postcode", "order_bil_tel", "order_bil_email");
			break;
	}
	
	var error = false;
	
	var normalClass = "textfield";
	var invalidClass = "textfield_invalid";
	
	for (var i = 0; i < fieldRequired.length; i++){
		var obj = formobj.elements[fieldRequired[i]];
		if(obj) {
			obj.className = normalClass;
		}
	}
	
	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 == 0 || obj.options[obj.selectedIndex].text == ""){
					obj.className = invalidClass;
					error = true;
				}
				break;
				case "select-multiple":
					if (obj.selectedIndex == -1){
					obj.className = invalidClass;
					error = true;
				}
				break;
				case "text":
				case "textarea":
				if (obj.value == "" || obj.value == null){
					obj.className = invalidClass;
					error = true;
				}
				break;
				default:
			}
		}
	}
	
	if (!error){
		
		return true;
		
	} else {
		
		alert("Some fields were not filled in. Please complete the highlighted fields.");
		return false;
		
	}
}



/*function getSelection(ta)
  { var bits = [ta.value,'','','']; 
    if(document.selection)
      { var vs = '#$%^%$#';
        var tr=document.selection.createRange()
        if(tr.parentElement()!=ta) return null;
        bits[2] = tr.text;
        tr.text = vs;
        fb = ta.value.split(vs);
        tr.moveStart('character',-vs.length);
        tr.text = bits[2];
        bits[1] = fb[0];
        bits[3] = fb[1];
      }
    else
      { if(ta.selectionStart == ta.selectionEnd) return null;
        bits=(new RegExp('([\x00-\xff]{'+ta.selectionStart+'})([\x00-\xff]{'+(ta.selectionEnd - ta.selectionStart)+'})([\x00-\xff]*)')).exec(ta.value);
      }
     return bits;
  }*/

function matchPTags(str)
  { str = ' ' + str + ' ';
    ot = str.split(/\[[B|U|I].*?\]/i);
    ct = str.split(/\[\/[B|U|I].*?\]/i);
    return ot.length==ct.length;
  }

function addPTag(ta,pTag)
  { bits = getSelection(ta);
    if(bits)
      { if(!matchPTags(bits[2]))
          { alert('\t\tInvalid Selection\nSelection contains unmatched opening or closing tags.');
            return;
          }
        ta.value = bits[1] + '[' + pTag + ']' + bits[2] + '[/' + pTag + ']' + bits[3];
      }
  }
  

		
function select_fabric(fabric_id, title, price, img){
		
	document.getElementById('fabric_id').value = fabric_id;
	document.getElementById('fabric_title').innerHTML = title;
	document.getElementById('request_sample_price').innerHTML = price;
	document.getElementById('fabric_options').style.display = 'none';
	document.getElementById('request_sample_chosen').style.display = 'block';
	document.getElementById('selectedimg').src = 'uploads/images/swatches/' + img;
	
}
		
function deselect_fabric(){
		
	document.getElementById('fabric_id').value = '';
	document.getElementById('fabric_title').innerHTML = '';
	document.getElementById('request_sample_price').innerHTML = '';
	document.getElementById('fabric_options').style.display = 'block';
	document.getElementById('request_sample_chosen').style.display = 'none';
	document.getElementById('selectedimg').src = '';
}


function show_fabric_selection(product_id){
	
	var id_fabric_options = 'fabric_options_' + product_id;
	document.getElementById(id_fabric_options).style.display = 'block';
	
}

function select_fabric_assoc(product_id, title, fabric_id, price, img){
	
	var id_fabric_id = 'fabric_id_' + product_id;
	var id_fabric_title = 'fabric_title_' + product_id;
	var id_request_sample_price = 'request_sample_price_' + product_id;
	var id_fabric_options = 'fabric_options_' + product_id;
	var id_request_sample_chosen = 'request_sample_chosen_' + product_id;
	var id_selectedimg = 'selectedimg_' + product_id;
	
	document.getElementById(id_fabric_id).value = fabric_id;
	document.getElementById(id_fabric_title).innerHTML = title;
	document.getElementById(id_request_sample_price).innerHTML = price;
	document.getElementById(id_fabric_options).style.display = 'none';
	document.getElementById(id_request_sample_chosen).style.display = 'block';
	document.getElementById(id_selectedimg).src = 'uploads/images/swatches/' + img;
	
}

function deselect_fabric_assoc(product_id){
	
	var id_fabric_id = 'fabric_id_' + product_id;
	var id_fabric_title = 'fabric_title_' + product_id;
	var id_fabric_price = 'fabric_price_' + product_id;
	var id_request_sample_price = 'request_sample_price_' + product_id;
	var id_fabric_options = 'fabric_options_' + product_id;
	var id_request_sample_chosen = 'request_sample_chosen_' + product_id;
	var id_selectedimg = 'selectedimg_' + product_id;
	
	document.getElementById(id_fabric_id).value = 0;
	document.getElementById(id_fabric_title).innerHTML = '';
	document.getElementById(id_request_sample_price).innerHTML = '';
	document.getElementById(id_fabric_options).style.display = 'block';
	document.getElementById(id_request_sample_chosen).style.display = 'none';
	document.getElementById(id_selectedimg).src = 'uploads/images/swatches/' + img;
	
}

function ismaxlength(obj){
var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
if (obj.getAttribute && obj.value.length>mlength)
obj.value=obj.value.substring(0,mlength)
}

function delivery_populate(){
	
	document.getElementById('delivery_firstname').value = document.getElementById('firstname').value;
	document.getElementById('delivery_surname').value = document.getElementById('surname').value;
	document.getElementById('delivery_address1').value = document.getElementById('address1').value;
	document.getElementById('delivery_address2').value = document.getElementById('address2').value;
	document.getElementById('delivery_address3').value = document.getElementById('address3').value;
	document.getElementById('delivery_town').value = document.getElementById('town').value;
	document.getElementById('delivery_county').value = document.getElementById('county').value;
	document.getElementById('delivery_postcode').value = document.getElementById('postcode').value;
	
}

function checkfabric(){
	
	if (document.getElementById('fabric_id').value == ''){
		
		alert('Please choose a fabric option');
		return false;
	
	} else {
		
		return true;	
		
	}
	
}

function checkfabric_assoc(product_id){
	
	var id_fabric_id = 'fabric_id_' + product_id;
	var id_fabric_options = 'fabric_options_' + product_id;
	var id_request_sample_chosen = 'request_sample_chosen_' + product_id;
	
	if (document.getElementById(id_fabric_options).style.display = 'none'){
		document.getElementById(id_fabric_options).style.display = 'block';
	}
	
	if (document.getElementById(id_fabric_id).value == ''){
		
		alert('Please choose a fabric option');
		return false;
	
	} else {
		document.getElementById(id_fabric_options).style.display = 'none';
		return true;	
		
	}
	
}


function sampleTallyCheck(){

	var tally = 0;
	
	var fields = document.getElementsByTagName('input');
	
	for(var i=0; i<fields.length; i++)
		{
			
			if ((fields[i].getAttribute('type')=='checkbox') && (fields[i].checked == true)){
			
				tally++;
				
				if (tally > 5) fields[i].checked = false;
				
			}
			
		}
		
	if (tally > 5){
		
		alert ('You have selected five samples.');
		
		return false;
		
	}

}


function confirmSubmit(){

	var agree=confirm("Are you sure you wish to delete this item?");

	if (agree)

		return true ;

	else

		return false ;

}

function bookmark(url,title){
  if ((navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 4)) {
  window.external.AddFavorite(url,title);
  } else if (navigator.appName == "Netscape") {
    window.sidebar.addPanel(title,url,"");
  } else {
    alert("Press CTRL-D (Netscape) or CTRL-T (Opera) to bookmark");
  }
}


function checkAll(id, checked){
	
	var length = id.length;
	
	var fields = document.getElementsByTagName('input');
	
	for(var i=0; i<fields.length; i++)
		{
			
			if (fields[i].getAttribute('type') == 'checkbox'){
				
				var theid = fields[i].getAttribute('name');
				if (theid.substring(0, length) == id) fields[i].checked = checked;
				
			}
			
		}
		
}