var cols;
var sel = new Array;

var editPage="";

function go(formId) {
	form = document.getElementById(formId);
	form.submit();
}

function closePopWin() {
//	hidePopWin(false);
	var actionField = document.getElementById("action");
	var form = actionField.form;
	form.submit();
}

function showEditPage(page) {
	if(editPage!="") {
		var lastPage = document.getElementById("subPage_"+editPage);
		lastPage.style.display = 'none';
	}
	showPage = document.getElementById("subPage_"+page);
	showPage.style.display = '';
	editPage = page;

	var currentPage = document.getElementById("pageName");
	currentPage.value = page;

}

var selectedTracks;
function selectTrack(disc,id) {

	var inputFieldName = "disc_"+disc;
	var imageFieldName = "discimage_"+disc+"_"+id;
	inputField = document.getElementById(inputFieldName);

	var currentValue = inputField.value;
	var re = new RegExp(".*"+id+".*","g");

	r = currentValue.search(re);
	image = document.getElementById(imageFieldName);
	if(r==false) {
		newVal = currentValue.replace(","+id,"");
		inputField.value = newVal; 
		image.src = 'http://development/colville/onedesk/style/sttw/images/tick_box_off.gif';
	} else {
		inputField.value = inputField.value + "," + id;
		image.src = 'http://development/colville/onedesk/style/sttw/images/tick_box_down.gif';
	}

}


function dispSubClass(field,action,urn) {
	var actionField = document.getElementById("action");
	actionField.value = "dispSubClass";
	var subField = document.getElementById("subField");
	subField.value = field;
	var subAction = document.getElementById("subAction");
	subAction.value = action;
	var subUrnField = document.getElementById("subUrn");
	subUrnField.value = urn;
	var form = actionField.form;
	form.submit();
}


function dispSelect(field) {
	var action = document.getElementById("action");
	var subField = document.getElementById("subField");
	action.value = "dispSelect";
	subField.value = field;
	var form = action.form;
	form.submit();
}


function removePick(field,pickUrn) {
	var action = document.getElementById("action");
	var pickField = document.getElementById("pickField");
	var pickUrnField = document.getElementById("pickUrn");
	action.value = "removePick";
	pickField.value = field;
	pickUrnField.value = pickUrn;
	var form = action.form;
	form.submit();
}

function addPick(field,pickUrn) { 
	var docParent = window.frameElement.ownerDocument;
	var action = docParent.getElementById("action");
	var pickField = docParent.getElementById("pickField");
	var pickUrnField = docParent.getElementById("pickUrn");
	action.value = "addPick";
	pickField.value = field;
	pickUrnField.value = pickUrn;
	var form = action.form;
	form.submit();
}

function mObject(){
   if (navigator.appName.indexOf ("Microsoft") !=-1){
    	return window["SingMovie"];
   }else{
    	return document["SingMovie"];
   }
}

function stop() {
   mObject().StopPlay();
}

function play() {
   mObject().Play();
}

function rewind() {
	var play = 0;	

	if(mObject().IsPlaying()){
		play=1;
	}

	mObject().GotoFrame(4);

	if(play==1) {
		mObject().Play();
	}
}

function pause() {
   if(mObject().IsPlaying()){
	    stop();
   }else{
    	play();
   }
}

function submitListForm(formName,listfield) {
	var action = document.getElementById("action_"+formName);
	if(action=="moveTo") {
		var moveTo  = document.getElementById("moveTo_"+formName);
		moveTo.value = listfield.option[listfield.value].id;
	}
	action.value = listfield.value;
	action.form.submit();
}

function submitForm(action,formName) { 
	var actionField = document.getElementById("action_"+formName);
	actionField.value = action;

	actionField.form.submit();
}

function submit(action) { 
	var actionField = document.getElementById("action");
	actionField.value = action;
	form = actionField.form;
	form.submit();
}

function doSubmit(action) { 
	var actionField = document.getElementById("action");
	actionField.value = action;
	form = actionField.form;
	form.submit();
}


var playTrack = false;
function playMP3(trackUrl) {
	if(playTrack) { stopTrack; playTrack=false; return; }
	Player.URL=trackUrl;
	playTrack = true;
}

function stopTrack() {
	Player.controls.stop();
}

function highlightRow(row,on) {
	var cell;
	for(i=0;i<cols;i++) {
		name = "cell"+row+"_"+i;
		cell = document.getElementById(name);
		if(on) {
			if(sel[row]) {
				cell.className="tableDataSelected";
			} else {
				cell.className="tableDataOver";
			}
		} else {
			if(sel[row]) {
				cell.className="tableDataSelected";
			} else {
				if((row%2)==0) {
					end="Even";
				} else {
					end = "Odd";
				}
				cell.className="tableData"+end;
			}
		}
	}
}

function selectRow(row) {
	if(sel[row]) {
		sel[row]=false;
	} else {
		sel[row]=true;
	}
	for(i=0;i<cols;i++) {
		name = "cell"+row+"_"+i;
		cell = document.getElementById(name);
		if(sel[row]) {
			cell.className="tableDataSelected";
		} else {
			if((row%2)==0) {
				end="Even";
			} else {
				end = "Odd";
			}
			cell.className="tableData"+end;
		}
	}
	
}


function showHide(id, forceHide) {
	var searchBox = document.getElementById(id);
	if (forceHide) {
		searchBox.style.display="none";
		return 0;
	}
	
	if(searchBox.style.display=="none") {
		searchBox.style.display="";
		return 1;
	} else {
		searchBox.style.display="none";
		return 0;
	}
}

function hide(id) {
	var searchBox = document.getElementById(id);
	if(searchBox == undefined) { return; }
	searchBox.style.display="none";
}

function minMax(id,minImg,maxImg) {

	showHide(id);
	var imgId = "img"+id;
	
	var searchBox = document.getElementById(id);
	var img = document.getElementById(imgId);
	if(searchBox.style.display=="none") {
		img.src=maxImg;
	} else {
		img.src=minImg;
	}

}

function updateField(field,value,disp) {
	var searchBox = window.frameElement.ownerDocument.getElementById(field);
	searchBox.value = value;
	var dispBox = window.frameElement.ownerDocument.getElementById("disp_"+field);
	dispBox.value = disp;
	parent.hidePopWin(false);
}

function resizeFrame(width,height) {
//alert(width+":"+height);
	if(width!="same") {
		window.frameElement.style.width = width;
	}
	if(height!="same") {
		window.frameElement.style.height = height;
	}
}


function addTrack(id) {
//	var pickDisp = window.frameElement.ownerDocument.frames["pickDisp"];
	var pickDisp = document.frames["pickDisp"];
	var pickRef = pickDisp.document.getElementById("pickRef");
	pickRef.value = id;
	pickRef.form.submit();

}


function pick_select(id, all) {
	var target = document.getElementById(id+"_selected");
	var source = document.getElementById(id+"_avail");	
	
	var tpos = target.options.length;
	
	
	for(i=0;i<source.options.length;) {
		if(source.options[i].selected || all) {
			target.options[tpos] = new Option(source.options[i].text,source.options[i].value);
			target.options[tpos].selected = true;
			
			tpos++;
		    
			source.options[i] = null;
			i=0;
		} else {
			i++;
		}
	}
	updateSelectHidden(id);
}

function updateSelectHidden(id) {

	var target = document.getElementById(id+"_selected");
	var hidden = document.getElementById(id);
	
	hidden.value = "";
	for(i=0;i<target.options.length;i++) {
		hidden.value = hidden.value + "," +target.options[i].value;
	}

}

function pick_unselect(id, all) {
	var source = document.getElementById(id+"_selected");
	var target = document.getElementById(id+"_avail");	
	
	var tpos = target.options.length;
	
	for(i=0;i<source.options.length;) {
		if(source.options[i].selected || all) {
			target.options[tpos++] = new Option(source.options[i].text,source.options[i].value);
			source.options[i] = null;
			i=0;
		} else {
			i++;
		}
	}
	updateSelectHidden(id);
}

function minimizeWin() 
{
window.resizeTo(100,100);
window.moveTo(screen.width,screen.height);
}

function maximizeWin() 
{
window.resizeTo(screen.width,screen.height);
window.moveTo(0,0);
}

function openWindow(url,name,height,width,xpos,ypos) {
	window.open(url,name,"scrollbars=1,width="+width+",height="+height+",top="+ypos+",left="+xpos);
}

var UniqueID = 314 // Make each link open in a new window 
var newWinOffset = 0 // Position of first pop-up

function PlayerOpen(soundfiledesc,soundfilepath) {
	PlayWin = window.open('',UniqueID,'width=320,height=190,top=' + newWinOffset +',left=0,resizable=0,scrollbars=0,titlebar=0,toolbar=0,menubar=0,status=0,directories=0,personalbar=0');
	PlayWin.focus(); 
	
	var winContent = "<HTML><HEAD><TITLE>" + soundfiledesc + "</TITLE></HEAD><BODY bgcolor='#FF9900'>"; 
	winContent += "<B style='font-size:18px;font-family:Verdana,sans-serif;line-height:1.5'>" + soundfiledesc + "</B>";
	
	winContent += "<OBJECT width='300' height='42'>"; 
	winContent += "<param name='SRC' value='" + soundfilepath + "'>";
	winContent += "<param name='AUTOPLAY' VALUE='true'>"; 
	winContent += "<param name='CONTROLLER' VALUE='true'>";
	winContent += "<param name='BGCOLOR' VALUE='#FF9900'>"; 
	winContent += "<EMBED SRC='" + soundfilepath + "' AUTOSTART='TRUE' LOOP='FALSE' WIDTH='300' HEIGHT='42' CONTROLLER='TRUE' BGCOLOR='#FF9900'></EMBED>";
	winContent += "</OBJECT>"; 
	
	winContent += "<p style='font-size:12px;font-family:Verdana,sans-serif;text-align:center'><a href='" + soundfilepath +"'>Download this file</a> <SPAN style='font-size:10px'>(right-click or Option-click)</SPAN></p>";
	winContent += "<FORM><DIV align='center'><INPUT type='button' value='Close this window' onclick='javascript:window.close();'></DIV></FORM>"; 
	winContent += "</BODY></HTML>"; 
	
	PlayWin.document.write(winContent); 
	PlayWin.document.close(); // "Finalizes" new window 
	UniqueID = UniqueID + 1 // newWinOffset = newWinOffset + 20 // subsequent pop-ups will be this many pixels lower 
} 

function changeActionAndSubmitForm (formName,url) {
	var form = document.getElementById(formName);
	form.action=url; 
	form.submit();
}

function updateFinalAdjustment(input, output, instock, direction) {
	var inputField = document.getElementById(input);
	var outputField = document.getElementById(output);
	
	if (!isNaN(inputField.value)) { 
		if ( inputField.value > 0 ) {		
			if (direction == 'increase') {
				var total = parseInt(instock) + parseInt(inputField.value);
			} else {
				var total = parseInt(instock) - parseInt(inputField.value);
			}
			if (total > 0) {
				outputField.style.color ='black';
			} else {
				outputField.style.color ='red';
			}
		} else {
			var total = "Number must be positive";
			outputField.style.color ='red';	
		}
	} else {
		var total = "Please enter a number";
		outputField.style.color ='red';
	}
	
	outputField.value=total;
	if (outputField.value == 'NaN') { outputField.value = ''; }
}

function printPage() {
    window.print();
}

function embeddedSoundFix() {
	//put this function straight after your embedded sound object
	objects = document.getElementsByTagName('object');
	for (var i = 0; i < objects.length; i++)
	{
		objects[i].outerHTML = objects[i].outerHTML;
	}
}

function showSubProduct(img, text, type, ref) {
	text.replace("`|`","'");
	if (document.getElementById('prodImg')) {
		document.getElementById('prodImg').src = img;
	}
	if(document.getElementById('productDesc')) {
		document.getElementById('productDesc').innerHTML = text;
	}
	if(document.getElementById('viewLargeImage')) {
		document.getElementById('viewLargeImage').href = "javascript:openPopup(\"index.php?task=getImage&action=displayProductImage&type="+type+"&ref="+ref+"&size=large\");";
	}	
}

function rowChangeClass(table,cols,row,classname) {
        for(i=1;i<cols;i++) {
alert(table+row+"_"+i);
                document.getElementById(table+row+"_"+i).className = classname;
        }
}

function showHideHelp(helpId) {
	var text = document.getElementById('pageHelpText_'+helpId);
	if(text.style.display == 'block') {
		document.getElementById('pageHelpImage_'+helpId).src = '/style/riders/images/help/help_down.gif';
		text.style.display = 'none';

		var field = 'pageHelp_'+helpId;
		var fieldWidget = document.getElementById(field);
		var scrollHeight = parseInt(text.scrollHeight);
		var height = parseInt(text.style.height.replace('px',''));
		var containerHeight = parseInt(fieldWidget.style.height.replace('px',''));

		var offset = containerHeight + scrollHeight;
		//alert(containerHeight + ':' + scrollHeight + ':' +  height);
	
		fieldWidget.style.overflow = 'hidden';
	
		text.style.overflow = 'hidden';

		expandElement(field, -10, 40, 30)
	} else {
		document.getElementById('pageHelpImage_'+helpId).src = '/style/riders/images/help/help_up.gif';
		text.style.display = 'block';
		
		var field = 'pageHelp_'+helpId;
		var fieldWidget = document.getElementById(field);
		var scrollHeight = parseInt(text.scrollHeight);
		var height = parseInt(text.style.height.replace('px',''));
		var containerHeight = parseInt(fieldWidget.style.height.replace('px',''));

		var offset = containerHeight + scrollHeight;
		//alert(containerHeight + ':' + scrollHeight + ':' +  height);
	
		fieldWidget.style.overflow = 'hidden';
	
		text.style.overflow = 'hidden';

		expandElement(field, 10, 40, offset)
	}			
	//readMore.style.display = 'none';
}

function expandElement(elName, increase, sec, highest) {
	el = document.getElementById(elName);
	el.style.display = 'block';

	el.style.height.replace('px','');
	var tempHeight = parseInt(el.style.height) + parseInt(increase);

	if (tempHeight != highest) {

		x = highest - tempHeight;
		if ( x <= increase ) {
			el.style.height = highest;
		} else {
			el.style.height = tempHeight;
			setTimeout("expandElement('"+elName+"', "+increase+", "+sec+", "+highest+")", sec );
		}
	}

}


/* EXPAND REDUCE MENU*/
function expandWidth(idElement,width,speed,initialWidth,expandingName, reducingName) {

        // Change the backgroundImage of the div that expands
        var reducing = document.getElementById(reducingName);
        reducing.style.backgroundImage = "url('/style/till_default/images/arrow_left.gif')";
        reducing.style.width = "7px";
        
        // Change the backgroundImage of the div that reduces
        var expanding = document.getElementById(expandingName);
        expanding.style.backgroundImage = "";
        expanding.style.width = "0px";

    var elementToExpand = document.getElementById(idElement);

    // The content of the div will not be displayed if it doesn't fit into
    elementToExpand.style.overflow = 'hidden';

    var previousWidth = elementToExpand.style.width;
    previousWidth = previousWidth.substring(0,previousWidth.length-2);

    var newWidth = Number(previousWidth) + Number(width);
    elementToExpand.style.width = newWidth;

    if(newWidth>Number(initialWidth)) {
        elementToExpand.style.width = initialWidth+"px";

    } else if(newWidth<Number(initialWidth)){
		setTimeout("expandWidth('"+idElement+"',"+width+","+speed+","+initialWidth+",'"+expandingName+"','"+reducingName+"')",speed);
    }
}

function reduceWidth(idElement,width,speed,minimumWidth,expandingName, reducingName) {

    var elementToReduce = document.getElementById(idElement);
    // The content of the div will not be displayed if it doesn't fit into
    elementToReduce.style.overflow = 'hidden';

    var previousWidth = elementToReduce.style.width;

    previousWidth = previousWidth.substring(0,previousWidth.length-2);
    var newWidth = Number(previousWidth) - Number(width);

//alert(elementToReduce.style.width);
    if(newWidth<Number(minimumWidth)) {
        elementToReduce.style.width = minimumWidth+"px";

        // Change the backgroundImage of the div that expands
        var expanding = document.getElementById(expandingName);
        expanding.style.backgroundImage = "url('/style/till_default/images/arrow_right.gif')";
        expanding.style.width = "7px";
        
        // Change the backgroundImage of the div that reduces
        var reducing = document.getElementById(reducingName);
        reducing.style.backgroundImage = "";
        reducing.style.width = "0px";
        
    } else if(newWidth>0){
	    elementToReduce.style.width = newWidth+"px";
		setTimeout("reduceWidth('"+idElement+"',"+width+","+speed+","+minimumWidth+",'"+expandingName+"','"+reducingName+"')",speed);
    }
}

function changeCursor(id,cursorValue) {
    var element = document.getElementById(id);
    element.style.cursor = cursorValue;
}

function hasWidth(idEl, width) {
    var el = document.getElementById(idEl);
    var widthEl = el.style.width.replace('px','');
    return (parseInt(widthEl) >= parseInt(width) );
}

function update_tillInput(hideEl, inputFieldName, hideFocus,form,action) {
	var ae = document.getElementById(hideEl);
	var inputField = document.getElementById(inputFieldName);
	var inputField_current = document.getElementById(inputFieldName+'_current');
	
	//validating input here
	var validation = validate_tillInput(inputField.value,action);
	if (validation != true) {
		alert(validation);
		inputField.select();
		inputField.focus();
		return;
	}
	
	inputField_current.innerHTML = inputField.value;

	ae.style.display="none";
	document.getElementById(hideFocus).focus();
	if (form && action) {
		window.location="pos://keyboard.hide";
		changeActionAndSubmitForm (form,"index.php?task=tillNewOrder&action="+action);
	}
}

function validate_tillInput(input,action) {
	var _return = false;
	switch(action) {
		case "processCash": 
			if (isInteger(input) && (input > 0) ) {
//		alert(input+">="+document.getElementById("totalOrderValue").value);
//		alert(input >= document.getElementById("totalOrderValue").value);
				input *= 1;
				var totalOrderValue = document.getElementById("totalOrderValue");
				totalOrderValue = totalOrderValue.value * 1;
				if ( input >= totalOrderValue ) {
					_return = true;
				} else {
					_return = "Cash amount is less than order total.";
				}
			} else {
				_return = "Please enter a number";
			}
			break;
		default: 
			_return = true;
	}
	return _return;
}

function isIntegerInRange (s, a, b) {   
	if (isEmpty(s))
	if (isIntegerInRange.arguments.length == 1) return false;
	else return (isIntegerInRange.arguments[1] == true);

	// Catch non-integer strings to avoid creating a NaN below,
	// which isn't available on JavaScript 1.0 for Windows.
	if (!isInteger(s, false)) return false;

	// Now, explicitly change the type to integer via parseInt
	// so that the comparison code below will work both on
	// JavaScript 1.2 (which typechecks in equality comparisons)
	// and JavaScript 1.1 and before (which doesn't).
	var num = parseInt (s);
	return ((num >= a) && (num <= b));
}

function isInteger (s) {
	var i;

	if (isEmpty(s))
	if (isInteger.arguments.length == 1) return 0;
	else return (isInteger.arguments[1] == true);
	
	for (i = 0; i < s.length; i++) {
		var c = s.charAt(i);
		if (!isDigit(c)) return false;	
	}

	return true;
}

function isEmpty(s) {
	return ((s == null) || (s.length == 0))
}

function isDigit (c) {
	return ((c >= "0") && (c <= "9") || c == ".")
}

function showHide_tillInput(hideEl, resetFieldName, resetValue, showFocus, hideFocus) {
	var ae = document.getElementById(hideEl);
	var resetField = document.getElementById(resetFieldName);
	var resetField_current = document.getElementById(resetFieldName+'_current');

	if(ae.style.display=="none") {
		ae.style.display="";
		resetField.value = resetValue;
		if(resetField_current) {
			resetField_current.innerHTML = resetValue;
		}
		document.getElementById(showFocus).focus();
		document.getElementById(showFocus).select();
		window.location="pos://keyboard.show";
	} else {
		ae.style.display="none";
		document.getElementById(hideFocus).focus();
		window.location="pos://keyboard.hide";
	}
}

function showHide_tillKeyBoard(hideEl, resetFieldName, resetValue, afterFocus) {
	var ae = document.getElementById(hideEl);
	var resetField = document.getElementById(resetFieldName);
	var resetField_current = document.getElementById(resetFieldName+'_current');
	if(ae.style.display=="none") {
		ae.style.display="";
		resetField.value = resetValue;
		if(resetField_current) {
			resetField_current.innerHTML = resetValue;
		}
	} else {
		ae.style.display="none";
	}
	document.getElementById(afterFocus).focus();
}

function till_updateField(fieldName, action) {
	var field = document.getElementById(fieldName);
	if(field.form.action.indexOf("\?") == -1) {
		field.form.action = field.form.action +'?action='+ action
	} else {
		field.form.action = field.form.action +'&action='+ action
	}
	field.form.submit();
}

function CopyPlusSelect(text) {
      var copyText = text;
      if (window.clipboardData) { // IE send-to-clipboard method.
            window.clipboardData.setData('Text', copyText);
      } else if (window.netscape) {
			if (!testFFSecurity()) { return false; }
			
            // You have to sign the code to enable this or allow the action in about:config by changing user_pref("signed.applets.codebase_principal_support", true);
            netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
            
            // Store support string in an object.
            var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
            if (!str) return false;
            str.data=copyText;
            
            // Make transferable.
            var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
            if (!trans) return false;
            
            // Specify what datatypes we want to obtain, which is text in this case.
            trans.addDataFlavor("text/unicode");
            trans.setTransferData("text/unicode",str,copyText.length*2);
            
            var clipid=Components.interfaces.nsIClipboard;
            var clip = Components.classes["@mozilla.org/widget/clipboard;1"].getService(clipid);
            if (!clip) return false;
            
            clip.setData(trans,null,clipid.kGlobalClipboard);
      }
}

function testFFSecurity() {
	try {
		var xx = netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
		return true;
	} catch(e) {
		return false;
	}
}

function ToDoNoteEdit(){
	var actions=document.getElementById("actionType");
	var users=document.getElementById("actionFor");
	var dueDate=document.getElementById("dueDate");
	var dueTime=document.getElementById("dueTime");
	var actionText=document.getElementById("actionDetails");

	if(actions.value==0) {
		users.disabled=true;
		dueDate.disabled=true;
		actionText.disabled=true;
	}else{
		users.disabled=false;
		dueDate.disabled=false;
		actionText.disabled=false;
	}
}

function autoIframe(frameId){
	try{
		frame = document.getElementById(frameId);
		innerDoc = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;
		objToResize = (frame.style) ? frame.style : frame;
		objToResize.height = innerDoc.body.scrollHeight + 10;
		objToResize.style.visibility = "visible";
	} catch(err){
		//window.status = err.message;
	}
}

