// Bookmarking
function bookmarkPage(title, url){
	if (document.all)
	window.external.AddFavorite(url, title);
	else if (window.sidebar)
	window.sidebar.addPanel(title, url, "");
}

// Open Pop-Up Window
function openWindow(theURL,winName,features) {
  window.open(theURL,winName,features);
}

// Pop Up Window
var newwindow;
function popup(url)
{
	newwindow=window.open(url,'name','height=400,width=485, scrollbars=yes, toolbar=no, menubar=no, resizable=yes');
	if (window.focus) {newwindow.focus()}
}
function popuppic(url)
{
	newwindow=window.open(url,'name','height=510,width=510, scrollbars=no, toolbar=no, menubar=no, resizable=yes');
	if (window.focus) {newwindow.focus()}
}

// Navigation for IE
navHover = function() {
	var navLi = document.getElementById("nav").getElementsByTagName("LI");
	for (var i=0; i<navLi.length; i++) {
		navLi[i].onmouseover=function() {
			this.className+=" over";
		}
		navLi[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" over\\b"), "");
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", navHover);


//Form Checker
function checkform ( form )
{
  // see http://www.thesitewizard.com/archive/validation.shtml
  // for an explanation of this script and how to use it on your
  // own website

  // ** START **
   if (form.name.value == "") {
   alert( "Please enter your Name." );
   form.name.focus();
   return false ;
 }
  if (form.email.value == "") {
    alert( "Please enter your email address." );
    form.email.focus();
    return false ;
  }
 if (form.telephone.value == "") {
   alert( "Please enter Telephone." );
   form.telephone.focus();
   return false ;
 }
 if (form.address.value == "") {
   alert( "Please enter Address." );
   form.address.focus();
   return false ;
 }
  // ** END **
  return true ;
}

//Form Checker Flash Page
function checkformflash ( form )
{
  // see http://www.thesitewizard.com/archive/validation.shtml
  // for an explanation of this script and how to use it on your
  // own website

  // ** START **
   if (form.form2mail_name.value == "") {
   alert( "Please enter your Name." );
   form.form2mail_name.focus();
   return false ;
 }
  if (form.form2mail_email.value == "") {
    alert( "Please enter your email address." );
    form.form2mail_email.focus();
    return false ;
  }
   if (form.form2mail_project_name.value == "") {
    alert( "Please enter the project name." );
    form.form2mail_email.focus();
    return false ;
  }
 if (form.form2mail_tel.value == "") {
   alert( "Please enter Telephone." );
   form.form2mail_tel.focus();
   return false ;
 }
 if (form.form2mail_address.value == "") {
   alert( "Please enter Address." );
   form.form2mail_address.focus();
   return false ;
 }
 if (form.form2mail_samples.value == "") {
   alert( "Please enter required samples." );
   form.form2mail_samples.focus();
   return false ;
 }

var radio_choice = false;
// Loop from zero to the one minus the number of radio button selections
for (counter = 0; counter < form.form2mail_thickness.length; counter++)
{
// If a radio button has been selected it will return true
// (If not it will return false)
if (form.form2mail_thickness[counter].checked)
radio_choice = true; 
}

if (!radio_choice)
{
// If there were no selections made display an alert box 
alert("Please select a thickness.")
return (false);
}

  // ** END **
  return true ;
}

//Form Checker Quote Tool Regisrer
function checkformregister ( form )
{

  // ** START **
   if (form.form2mail_name.value == "") {
   alert( "Please enter your Name." );
   form.form2mail_name.focus();
   return false ;
 }
  if (form.form2mail_email.value == "") {
    alert( "Please enter your email address." );
    form.form2mail_email.focus();
    return false ;
  }
 if (form.form2mail_tel.value == "") {
   alert( "Please enter Telephone." );
   form.form2mail_tel.focus();
   return false ;
 }
 if (form.form2mail_address.value == "") {
   alert( "Please enter Address." );
   form.form2mail_address.focus();
   return false ;
 }
 if (form.form2mail_company.value == "") {
   alert( "Please enter your company name." );
   form.form2mail_company.focus();
   return false ;
 }
 if (form.form2mail_registration.value == "") {
   alert( "Please enter your company registration number." );
   form.form2mail_registration.focus();
   return false ;
 }
  if (form.form2mail_website.value == "") {
   alert( "Please enter your website." );
   form.form2mail_website.focus();
   return false ;
 }
  // ** END **
  return true ;
}



//Create an array 
var allPageTags = new Array(); 

function hoverClass(quoteHover) {
//Populate the array with all the page tags
var allPageTags=document.getElementsByTagName("*");
//Cycle through the tags using a for loop
for (i=0; i<allPageTags.length; i++) {
//Pick out the tags with our class name
if (allPageTags[i].className==quoteHover) {
//Manipulate this in whatever way you want
allPageTags[i].onmouseover=function() {
			alert('boo!');
			this.className+=" over";
		}
		allPageTags[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" over\\b"), "");
		}
}
}
} 

// Bookmarking
function bookmark(url,title){
if (window.sidebar) // firefox
	window.sidebar.addPanel(title, url, "");
else if(window.opera && window.print){ // opera
	var elem = document.createElement('a');
	elem.setAttribute('href',url);
	elem.setAttribute('title',title);
	elem.setAttribute('rel','sidebar');
	elem.click();
} 
else if(document.all)// ie
	window.external.AddFavorite(url, title);
}

// Pop Up Window
var newwindow;
function sendToFriend(url)
{
	newwindow=window.open(url,'name','height=420, width=540, scrollbars=yes, toolbar=no, menubar=no, resizable=yes');
	if (window.focus) {newwindow.focus()}
}

// Duplicate Acrifix
/*function duplicateInput(x) {
	var y=document.getElementById(x).value
	document.getElementById("lname").value=y.toLowerCase()
	var a=document.getElementById(x).value
	document.getElementById("fname").value=a.toLowerCase()
}*/

function duplicateInput(x) {
	//alert(x);
	if(x=="acrifix_190") {
		var y=document.getElementById(x).value;
		document.getElementById("acrifix_120_catalyst").value=y.toLowerCase();
		//alert(x);
	}	
	if(x=="acrifix_120_catalyst"){
		var a=document.getElementById(x).value
		document.getElementById("acrifix_190").value=a.toLowerCase()
		//alert(x);
	}
}

// Helper for the Quote tool, creates new or duplicate rows in the given table
// @param   string      source      The ID of the containing table
// @param   boolean     as_new      Flag to indicate if the row should be cloned, or with new values.
function duplicateRow(source, as_new) {
    if (! $(source)) {
        return;
    }
    try {
        // Locate the target table and clone the last row.
        var rows = $(source).getChildren('tr');
        if (rows.length < 1) {
            // No rows found!
            return false;
        }
        var row = rows[rows.length - 1];
        var row2 = row.cloneNode(true);
        
        // Append to the DOM
        $(source).appendChild(row2);
        if (as_new == false) {
            // A cloned row, and this is an IE hack!
            var rowOpts = row.getElements('select');
            var row2Opts = row2.getElements('select');
            for(i = 0; i < rowOpts.length; i++){
                row2Opts[i].selectedIndex = rowOpts[i].selectedIndex;
                if (row2Opts[i].get('onchange')) {
                    //Need to add the correct class name
                    var opts = PPExclusion.getSelectProperties($(row2Opts[i]));
                    if (opts) {
                        row2Opts[i].removeClass(opts.orig);
                        row2Opts[i].addClass(opts.nextRow);
                    }
                }
            }
        }
        else {
            // A new row, so remove all selections copied from the old row.
            var ipts = row2.getElements('input');
            var opts = row2.getElements('select');
            for (var i = 0, l = ipts.length; i < l; i++) {
                ipts[i].set('value', '');
            }
            for (i = 0, l = opts.length; i < l; i++) {
                opts[i].selectedIndex = 0;
                //Need to add the correct class name
                var o = PPExclusion.getSelectProperties($(opts[i]));
                if (o) {
                    opts[i].removeClass(o.orig);
                    opts[i].addClass(o.nextRow);
                }
            }
        }
    } catch (e) {
        alert("Failed to find last row: " + e.message);
        return false;
    }
}

var PPExclusion = {

    values: [],

    hashedData: null,

    // onchange event handler for inputs which need guidance.
    onChangeHandler: function (input, changed_field) {
        var src_ipt = this.getSelectProperties($(input));
        if (src_ipt === false) {
            return;
        }
        // Set up the exclusion hashes, if required.
        this.createLocalExclusionHashes();

        // loop the exclusion rules to see if any of the field/value combinations
        var newval = input.get('value');
        for (var i = 0; i < this.hashedData.length; i++) {
            if (this.hashedData[i].get(src_ipt.field) == newval) {
                //check_hashes.push(this.hashedData[i]);
                if (this.newSelectionClashes(input, src_ipt, this.hashedData[i], src_ipt.field)) {
                    alert("This combination is invalid, please choose a different option");
                    input.options.item(0).selected = true;
                    return;
                }
            }
        }
    },



    // Helper method, checks whether the given input selection violates the current
    // exclusions rules.
    //
    // @param       DomNode     input       The 'select' element which generated the event
    // @param       Object      ipt_def     The class definition object for input (i.e. from getSelectProperties)
    // @param       Hash        rule_def    The hashed rule which could be violated.
    // @param       String      from_field  The field in rule_def whose value matches input
    newSelectionClashes: function (input, ipt_def, rule_def, from_field) {
        var keys = rule_def.getKeys().remove(from_field);

        for (var i = 0, l = keys.length; i < l; i++) {
            var key_rule = rule_def.get(keys[i]);
            var check_sib = null;
            if (key_rule == '*') {
                continue;
            }
            switch (keys[i]) {
            case 'edge_code':
                check_sib = this.getSiblingSelectClass(ipt_def, 'ec');
                var sibs = $$('.' + check_sib);

                for (var j = 0, m = sibs.length; j < m; j++) {
                    if (sibs[j].get('value') == rule_def.get(keys[i])) {
                        return true;
                    }
                }
                break;
            case 'colour':
                check_sib = this.getSiblingSelectClass(ipt_def, 'cl');
                var sibval = $$('.' + check_sib).get('value');
                if (sibval == rule_def.get(keys[i])) {
                    return true;
                }
                break;
            case 'material':
                check_sib = this.getSiblingSelectClass(ipt_def, 'mt');
                var sibval = $$('.' + check_sib).get('value');
                if (sibval == rule_def.get(keys[i])) {
                    return true;
                }
                break;
            case 'curved':
                if (ipt_def.row == 'curve') {
                    return true;
                }
                break;
            }
        }
        return false;
    },


    // Create some hashes out of the objects which the 
    createLocalExclusionHashes: function () {
        if (this.hashedData !== null || pp_exclusions === false) {
            return;
        }
        this.hashedData = [];
        for (var i = 0, l = pp_exclusions.length; i < l; i++) {
            this.hashedData.push(new Hash(pp_exclusions[i]));
        }
    },


    // Given an "expanded css class prototype" (i.e returned from getSelectProperties)
    // return a string for the 'sibling' class for the given subfield
    getSiblingSelectClass: function (proto, repl_field) {
        switch (proto.row) {
        case 'curve':
            repl_field = repl_field + 'c';
            break;
        case 'flat':
            repl_field = repl_field + 'f';
            break;
        case 'drawer':
            repl_field = repl_field + 'd';
            break;
        }
        return repl_field + proto.rownum.toString();
    },



    // Helper method to extract the row definition from the class on the
    // given input element.
    getSelectProperties: function (input) {
        var cls = input.get('class');
        if (! cls) {
            return false;
        }
        var ret = {}, buff = '';
        ret.orig = cls;
        // Get the field type
        switch (cls.substring(0, 2)) {
        case 'ec':
            buff = 'ec';
            ret.field = 'edge_code';
            break;
        case 'cl':
            buff = 'cl';
            ret.field = 'colour';
            break;
        case 'mt':
            buff = 'mt';
            ret.field = 'material';
            break;
        default:
            return false;
        }
        // Get the row type
        switch (cls.substring(2, 3)) {
        case 'f':
            buff += 'f';
            ret.row = 'flat';
            break;
        case 'c':
            buff += 'c';
            ret.row = 'curve';
            break;
        case 'd':
            buff += 'd';
            ret.row = 'drawer';
            break;
        default:
            return false;
        }
        // Finally, the row number
        ret.rownum = parseInt(cls.substring(3));
        var nr = ret.rownum + 1;
        ret.nextRow = buff + nr.toString();
        return ret;
    }
}
/*

Select element classes:
-----------------------

* First 2 chars are for select type:

ec = edge code
cl = colour
mt = material


* Third char gives the row type:
f = flat
c = curved
d = drawers etc.

* Fourth char (integer) gives the row number, starting from 1

Examples:
--------
ecf1 = edge code flat row 1
clc2 = colour curved row 2
mtd1 = material drawer row 1


Exclusion Definition Data
-------------------------

Exclusions are munged in to a JS object structure on the server,
here is an example of the output structure

var pp_exclusions = [
    {edge_code: '*', colour: '*', material: '4mm', curved: 'C'}, 
    {edge_code: 'FF10', colour: '*', material: '*', curved: 'C'}, 
    {edge_code: '*', colour: 'Anthracite', material: '4mm', curved: '*'}
]


*/

