/*
	This file contains any validation and menu choosing functions necessary for the operation of the CMS system
	Copyright 2004 Scion Solutions Ltd www.scion.co.uk
	Version 1.00 29/01/04
	Version 2.00 20/09/05
	Author: Ian Winstanley
*/

/* Browser detection */
var NS = (document.layers) ? 1 : 0;
var IE = (document.all) ? 1 : 0;
var NEW = (document.getElementById) ? 1 : 0;
var IE4 = (IE && !NEW) ? 1 : 0;
var IE5 = (IE && NEW) ? 1 : 0;
var MAC = (navigator.appVersion.indexOf("Mac") != -1) ? 1 : 0;
var Opera = (navigator.userAgent.indexOf("Opera") != -1) ? 1 : 0;
var Firefox = (navigator.userAgent.indexOf("Firefox") != -1) ? 1 : 0;
var NS6 = (NEW && !IE && !Opera & !Firefox) ? 1 : 0;



// Uses the DOM object to add more time values client side
function addRow(val, tableID) {
	var counter;
	var checkArray;
	counter = formOptionCounter;
	inputKeyName = 'sms_time_elapsed';

	var tb = document.getElementById(tableID).getElementsByTagName('tbody')[0];
	var tableRows = tb.rows;
	val = parseInt(val);
	var tableRowsLength = tb.rows.length
	var desiredRowLength = counter+val;

	if (counter+val < tableRowsLength) {
		for (j = desiredRowLength; j < tableRowsLength; j++) {
			if (tableRows[j]) {
				tb.removeChild(tableRows[j]);
				j--;
				tableRowsLength--;
			}
		}
	} else if (counter+val > tableRowsLength) {

		for (i = tableRowsLength; i < counter+val; i++) {

			var r = tb.getElementsByTagName('tr')[(i-1)].cloneNode(true);

			var td = r.getElementsByTagName('td')[0];
			var newtd = document.createElement("TD");
			r.replaceChild(newtd, td);

			var td1 = r.getElementsByTagName('td')[1];
			var oldInput = td1.getElementsByTagName('input')[0];
			var input = document.createElement("INPUT"); 
			input.setAttribute("type","text"); 
			input.setAttribute("size","50"); 
			input.setAttribute("name","new_label[]"); 
			td1.replaceChild(input, oldInput);

			var td2 = r.getElementsByTagName('td')[2];
			var oldInput = td2.getElementsByTagName('input')[0];
			var input = document.createElement("INPUT") 
			input.setAttribute("type","checkbox"); 
			input.setAttribute("name","new_mandatory[]"); 
			input.setAttribute("value","y"); 
			td2.replaceChild(input, oldInput);

			var td3 = r.getElementsByTagName('td')[3];
			var newtd3 = document.createElement("TD");
			var newSelect = document.createElement("SELECT");
			newSelect.setAttribute("name","new_field_type[]"); 
			var option1 = document.createElement("OPTION");
			theText=document.createTextNode("text");
			option1.appendChild(theText); 
			newSelect.appendChild(option1); 
			var option2 = document.createElement("OPTION");
			theText=document.createTextNode("textarea");
			option2.appendChild(theText); 
			newSelect.appendChild(option2);
			newtd3.appendChild(newSelect);
			r.replaceChild(newtd3, td3);

			tb.appendChild(r);

		}
	}
}

/* 
	Emulates the value of 'n' if the checkbox is not checked (in this case no value is sent through and we can't change 'y' to 'n' 
*/
function simulateUnchecked(fld, key) {
  if (fld.checked) {
    document.getElementById(key).disabled = true;
  } else {
    document.getElementById(key).disabled = false;
  }
}


/*
	Checks the amendments or additions to the contact form details
*/
function checkContactFormUpdate(frm) {
	Msg = '';
	if (frm['contact_form_details[id]']) {
		if (frm['contact_form_details[id]'].value == '') {
			Msg += 'Please enter an ID on order to identify the contact form\n';
		}
	}

	if (frm['contact_form_details[contact_name]'].value == '') {
		Msg += 'Please enter a contact name\n';
	}
	
	if (frm['contact_form_details[contact_email]'].value == '') {
		Msg += 'Please enter a contact email\n';
	}
	
	if (frm['contact_form_details[heading]'].value == '') {
		Msg += 'Please enter a heading\n';
	}
	
	if (frm['contact_form_details[description]'].value == '') {
		Msg += 'Please enter a description\n';
	}
	
	if (Msg) {
		alert(Msg);
		return false;
	} else {
		return true;
	}
}

/*
	Populates each option list based on
	1. The select object
	2. The value of the parent select that has been selected
	3. The array that pertains to the select or the next child
	4. Which indexes in the array above to use - ensures that options can be related without children in between having a relationship
	5. Even if the index does not match with the selected value if sellAll is called all options will be displayed
	6. Deselect the checkbox if set
*/
function populateSelect (chann, channValue ,arrayOb, arrayIndex, sellAll, deselectsellAll) {
	if (sellAll && deselectsellAll) { // If we are not submitting via the checkbox
		sellAll.checked = false;
	}

	if (arrayOb.length > 0) {
		j = 1;
		if (chann) {
			with (chann) {
				length = 1;
				for (var i in arrayOb) {
					if ((sellAll && sellAll.checked) || arrayOb[i][arrayIndex] == channValue.value || channValue.value == '') {
						length = j+1;
						options[j].value = arrayOb[i][0];
						options[j].text = arrayOb[i][1].replace(/\\/);
						j++;
					}
				}
			}
		}
	}
}

/*	
	Loops through the drop downs that denote where on the page a content item should be displayed
	and ensures that no two drop downs share the same value
*/
var previousSelectedIndex
function checkVals(frm, fld) {
	for (i = 0; i < frm.elements.length; i++) {
		if (frm.elements[i].name) {
			if (frm.elements[i].name.match(/display_order/)) {
				if (frm.elements[i].selectedIndex == fld.selectedIndex && frm.elements[i].name != fld.name) {
					frm.elements[i].selectedIndex = previousSelectedIndex;
				}
			}
		}
	}
	fld.blur();
}

// Confirm that the user wants to delete the records
function checkDelete(frm) {
	var j = 0, plur, thisPlur, alertQualification;
	if (frm.mode.value == 'delete_item' || frm.mode.value == 'check_in' || frm.mode.value == 'edit_page') {
		for (var i = 0; i < frm.elements.length; i++) {
			if (frm.elements[i].type == 'checkbox' && frm.elements[i].checked == true) {
			  j++;
			} else if (frm.elements[i].type == 'radio' && frm.elements[i].checked == true) {
			  j++;
			}
		}
		if (j == 0) {
			alert ('Please select at least one option');
			return false;
		}
		if (j > 1) {
		  plur = 's';
		  thisPlur = 'these';
		} else {
		  plur = '';
		  thisPlur = 'this';
		}
    	if (frm.mode.value == 'delete_item') {
    		alertQualification = 'delete ';
    	} else if (frm.mode.value == 'edit_page') {
    		alertQualification = 'rollback to ';
    	} else {
    		alertQualification = 'check in ';
    	}
		if (!confirm('Are you sure you want to ' + alertQualification + thisPlur + ' ' + j + ' record' + plur + '?')) {
			return false;
		}
	}
}

// For the FAQs
function checkCategory(fld) {
	if (fld.value == '') {
		alert('Please select a category for the FAQ');
		return false;
	} else {
		return true;
	}
}

// Alters the submit button value, mode value
function validate(elem, frm, inputType) {
   	if (inputType == 'radio' && elem.checked) {
      	    frm.mode.value = 'display';
      	    checkRadCheck(frm, 'checkbox')
    	} else if (inputType == 'checkbox' && elem.checked) {
      	    frm.mode.value = 'delete_item';
      	    checkRadCheck(frm, 'radio')
    	}
}
// Deselects any opposing form elements
function checkRadCheck(frm, type) {
    	for (var i =0; i < frm.elements.length; i++) {
    		if (frm.elements[i].type == type) {
    	  	  frm.elements[i].checked = false;
    		}
    	}
}

// Preload images
var myImages = new Array(); 
function preloadImages(imageName, imagePath) {
	for (var i in imageName) {
		myImages[imageName[i] + '_on'] = new Image();
		myImages[imageName[i] + '_on'].src  = imagePath + imageName[i] + '_on.gif';
		myImages[imageName[i] + '_off'] = new Image();
		myImages[imageName[i] + '_off'].src = imagePath + imageName[i] + '.gif';
	}
}

// Generic /images replace function
function imageChange(imgOb, imgReplace) {
	imgOb.src = myImages[imgReplace].src;
}

// Sets select boxes to the current day, month and year
function setDrops(daySel, mnthSel, yrSel) {
	var now = new Date();
	var day = now.getDate();
	var month = now.getMonth()+1; // numbered from 0
	var year = now.getFullYear();
	if (year < 1900) year += 1900; // or use getFullYear() in v4 browsers
	/* comment the following line out to remove the display of date */
	//document.write(now.toString()+'<br>'+year+'/'+month+'/'+day); 
   // Assume Day and months are all there and start with "Select a Day and Select a month
   daySel.selectedIndex = day;
   mnthSel.selectedIndex = month;
  // now the year will be slightly different
   var found = 0;
   for(i=1;i<yrSel.options.length;i++) {
      if (yrSel.options[i].text == year) {
         found =i;
         break;
      }
   }
   yrSel.selectedIndex =  found;
}

// opens a popup window based on either default or supplied arguments
var myWin, focusWin;
function openWindow(url, winWidth, winHeight, windowName) {
	var winWidth = winWidth ? winWidth : 800;
	var winHeight = winHeight ? winHeight : screen.height-300;
	var left = screen.width-810;
	var parms = 'toolbar=yes, location=yes, directories=no, status=no, menubar=yes, scrollbars=yes, resizable=yes, height=' + winHeight + ',width=' + winWidth + ', left=' + left + ', top=0';

	if (typeof focusWin == 'undefined') {
        	focusWin = window.open(url, 'myWin', parms);
	} else {
        	focusWin.location = url;
		focusWin.focus();
        }
}

