// Various tools for IG 4.x service

// Ident: $Id: ig.js 46965 2008-12-17 19:09:42Z rabrahamson $

// sets all the check boxes on the page to the passed
// value (true or false)
function setchecks(value) {
   for (var i = 0; true; i++) {
        if (!document.getElementById("checkbox"+i)) {
            return;
        }
        document.getElementById("checkbox"+i).checked = value;
   }  
}

// name: openJtk
// desc: opens job ticket window with the correct database
// job ticket id. (this is important).
// returns: true.
// notes: Most of the magic for this function (like changing
// label and setting the openedjtk var) is done in /jtk/attach.html
// when the job ticket is successfully attached.
function openJtk(fuid,frame) {
    var formid = document.getElementById("jt").value;
	var url = "/jtk/complete/" + formid + "/index.html?fuid="+fuid;
	
	if (typeof frame != "undefined" && frame != '') {
		window.frames[frame+'Iframe'].location = url;
	} else {
    	window.open(url, "jobticket");
	}

	return true;
}

// name: forwardJT
// desc: This is run via the onLoad event for the create package page
// it attempts to set the selected Job Ticket to "Forward Job Ticket"
// which then triggers a button label change and hiding the Job id/Client id 

function forwardJT() {
   for (var i = 0; i < document.getElementById("jt").length; i++) {
   		if (document.getElementById("jt").options[i].value == 1) {
   			document.getElementById("jt").options[i].selected = true;
            enableJtkButton(document.getElementById("jt"));
            return true;
   		}
   }
   return false;
}

// name: enableJtkButton
// desc: This enables the jtk button and changes 
// the text if it is a jtk already edited (meaning stored
// to the server.) It has expanded to include checking
// for the global var 'dest_reqs_jtk' which will change the
// current 'send' button from/to being disabled. 
function enableJtkButton(select) {
    var button = document.getElementById("jtkbutton");

    // not exists (we could check for numeric)
    // if current value of select is not set to none 
    // then enable button
    if (select.value.indexOf("none") == -1) {
        button.disabled = false; 
    } else {
        button.disabled = true; 
        // just in case reable job and client
        // id fields.
		show(document.getElementById("jobtr"));
        show(document.getElementById("clienttr"));
    }

    // switch the button label 
    if (select.value == openedjtk || select.value == 1) {
        setTxtReview(button);
        if (!document.getElementById("cbd_dupes") || document.getElementById("cbd_dupes").value == 0) {
			enableSendButton();
		}
        // hide job id
		hide(document.getElementById("jobtr"));
        hide(document.getElementById("clienttr"));
        document.getElementById("reqdjtk_msg").className = "small hide";
    } else {
        setTxtComplete(button);
		// global var for remembering if dest
		// requires job ticket to be attached.
		if (dest_reqs_jtk) { 
			disableSendButton();
			document.getElementById("reqdjtk_msg").className = "small";
        } else {
            if (!document.getElementById("cbd_dupes") || document.getElementById("cbd_dupes").value == 0) {
                enableSendButton();
            }
            document.getElementById("reqdjtk_msg").className = "small hide";
        }
    }

    return true;
}

// name: show
// desc: show element passed
// args: html element (return by getElementById())  
function show(e) {
	if (document.all) {
		e.style.display = "inline";
	} else {
		e.style.display = "table-row";
	}
}

function hide(e) {
    // this is really strange but since our current
    e.style.display = "none";
}

// this won't work if called from opener.* ...
function setTxtComplete(b) {
    var txt_complete = "Complete Job Ticket";
    //var txt_complete = document.getElementById("txt_complete").value;
    //var txt_complete = "Complete Job Ticket";
	// override the hard code value if one exists in the form
	if (document.getElementById("txt_complete")) {
		txt_complete = document.getElementById("txt_complete").value;
	}

    b.value = txt_complete; 
}

function setTxtReview(b) {
	var use_opener = false;
    var txt_review = "Review Job Ticket"; // txt to use

	// second arg is optional to indicate calling status
	if (arguments.length > 1) 
		use_opener = arguments[1];

	// use the opener object if set
	// load txt only if found.
	if (use_opener) {
		if (parent.document.getElementById("txt_review"))
			txt_review = parent.document.getElementById("txt_review").value;
	} else {
		if (document.getElementById("txt_review")) 
			txt_review = document.getElementById("txt_review").value;
	}

    //var txt_review = "Review Job Ticket";
    b.value = txt_review;
}

// name: moveSelect
// desc: moves html elements from one to another select thing.
// args: from - select html element, to - select html element. 
function moveSelect(from, to, old) {
    var newfromopts; // new options for from 
    // 
    for (var i = 0; i < from.options.length; i++) {
        if (from.options[i].selected) {
            // netscape allows us to move it to
            // the other thing.
            if (navigator.appName == 'Netscape') {
                var ni = to.options.length;
                to.options[ni] = from.options[i]; 
                to.options[ni].selected = false;
            } else {
            // IE -- piece of shit
                var oldopt = from.options[i];
                var opt = new Option(oldopt.text,
                                     oldopt.value,
                                     false,
                                     false);
                to.options.add(opt);
                from.options[i] = null;
            //to.options.add(from.options[i]);
            //alert("typeof: " + typeof(to.options));
            }
        }
    }
}

// *****************************************************
// Name: copySelect 
// Desc: copys the selected options in 'from' to 'to'
//    by creating now option objects. It will not copy
//    empty options (value="") so don't try it. ;)
// Args: 
//   from - select object (source)
//   to   - select object (dest) 
//   jtks  - job ticket object array (index of resource id)
//   java - true will call applet in page. 
//      ** This might be easier to just check for the applet **
// Returns: nothing of use
// Notes: may need to check for the current
// set style of from and to. (formatting CSS crap). 
// Need to do selecte from current from (from.options.selected = false)
// ** Need to add the jtks array/hash of job ticket objects **
// *****************************************************
function copySelect(from, to, jtks, java) {
    // walk options in select
    for (var i = 0; i < from.options.length; i++) {
        // if selected copy to new 
        if (from.options[i].selected) {
            var fopt = from.options[i]; // short hand
            var found = false;

			// must have something in the value (length >= 1)
			if (fopt.value.length < 1) 
				continue;

            // check for duplicates
            for (var k = 0; k < to.options.length; k++) {
                if (to.options[k].value == fopt.value) {
                    found = true;
                }
            } //check loop

            // only add if not found.
            if (!found) {
                var opt = new Option( fopt.text,
                                      fopt.value,
                                      false,
                                      false );
                // handle browsers that don't support
                // the add method (such as safari)
                if (to.options.add) {
                    to.options.add(opt);
                } else {
                    to.options[to.options.length] = opt;
                }

				var myjtk = jtks[getResId(opt.value)];
				if (!addJtkDesc(myjtk)) {
					var msg = document.getElementById("txt_reqd_conflict_error").value;
					if (!msg) 
						msg = "New destination has conflicting job ticket. Cannot Add.";
					to.options[to.options.length - 1].selected = true;
					delSelect(to, jtks, java);
					alert(msg);
					// fix browser bug
					fopt.selected = false;
					return true;
				}

				if (java) {
					// remove all 
					document.uploadapplet.clearDestinations();
					// add all
					for (var k = 0; k < to.options.length; k++) {
						document.uploadapplet.addDestination(to.options[k].value);
					} // add loop
				}
            } // only add if not found.

            //try to select the forwarded JT
            forwardJT();

            // de-select even if it already exists
            // in the to object.
            from.options[i].selected = false;
        }
    } // for loop
}

// name: delSelect
// desc: removes 
// args: 
// select - select option group to delete from
// jtks   - job ticket object array
// java   - boolean to remove and add all to applet.
function delSelect(select, jtks, java) {
	var deleted = false; // did we actually delete something?

    // walk to look for ones to remove
    for (var i = 0; i < select.options.length; i++) {
        // get rid of selected ones (this this goof up
        // the array walk? Do we need to build a list
        // or indexs to delete? is this or that reliable for 
        // multiples?
        if (select.options[i].selected) { 
			// remove dest
            select.options[i] = null;
			deleted = true;
        }

    }

	// only run if we  
	if (!deleted) {
		return true;
	}

	// when deleting a single item, just remove
	// all desc and add in resources that still have
	// values.
	delAllDesc();
    enableSendButton(); 
    enableJtkButton(document.getElementById("jt"));

    for (var i = 0; i < select.options.length; i++) {
			var value = select.options[i].value;
			var myjtk = jtks[getResId(value)];
			addJtkDesc(myjtk);
	}

	if (java) {
		// remove all (need to check document.uploadapplet exists...)
		document.uploadapplet.clearDestinations();
		// add all
		for (var k = 0; k < select.options.length; k++) {
			document.uploadapplet.addDestination(select.options[k].value);
		} // add loop
	}

	return false;
}

// name: selectAll
// desc: selects all options in select thingy. For use 
// on submit to make sure all send to are enabled.
// args: select thingy to select all from
//
function selectAll(s) {
    for (var i = 0; i < s.options.length; i++) {
        s.options[i].selected = true;
    }

    return true;
}

// name: setFormatCookie
// desc: sets the cookie 'IG_DL_FMT' with value passed 
// args: format value
function setFormatCookie(fmt) {
	var expire = new Date();

	expire.setFullYear(expire.getFullYear() + 1);
	document.cookie = "IG_DL_FMT=" + fmt + 
					  "; expires=" + expire.toGMTString() +
					  "; path=/;";
	return true; 
}

// name: setJtkError
// args: e - html element (type - div)
// desc: sets the className of html element to jtkError.
function setJtkError(e) {
	e.className = "jtkError";
}

// name: getResId
// args: address string from sendto/address book
//  address - 'pipe delimited string cid|cname|rid|rname'
// returns: resource id
function getResId(address)
{
	// 0 - cid, 1 - cname, 2 - rid, 3 - rname
	var info = address.split(/\|/);
	return(info[2]);

}

// name: disableSendButton
function disableSendButton()
{
	var id = "submitbutton"; // id to retrieve
	var button = document.getElementById(id);

	// did we find the button ?
	if (!button) {
		return false;
	}
button.disabled = true;
//	return(disableButton(button));
}

function enableSendButton()
{
	var id = "submitbutton"; // id to retrieve
	var button;
	var use_opener = false;

	if (arguments.length > 0) 
		use_opener = arguments[0];

	if (use_opener) {
		button = parent.document.getElementById(id);
	} else {
		button = document.getElementById(id);
	}

	if (!button) {
		return false;
	}

	return(enableButton(button));
}

function disableButton(button)
{
	if (!button) {
		return false;
	}

	button.disabled = true;
	return true;
}

function enableButton(button)
{
	if (!button) {
		return false;
	}

	button.disabled = false;
	return true;
}

// name: fileparse(path,detect)
// desc: returns array with three elements (if matched)
// index :
//      0 - path (string passed)
//      1 - dirname 
//      2 - filename 
// Note: acts upon unix paths only if unix is true, otherwise it detects windows and deals with it
function fileparse(path,unix)
{
	// rc[0] = path, rc[1] = dirname, rc[2] = filename
	// unix pattern
	var pattern = /^(.*\/)?(.*)/;

	if (navigator.platform.indexOf("Win") >= 0 && !unix) 
		pattern = /^(.*\\)?(.*)/;

	var rc = path.match(pattern);
	return(rc);
}

//  name:  dirname
//  desc: takes a path (for unix style paths) 
//   and returns the only the dir name. (much like the unix function)
function dirname(path)  
{
    var rc = fileparse(path);
    return(rc[1]);
}

// name: basename 
// desc:  takes a unix path and returns the file part (if found)
// i.e. /my/path/file - would return file
function basename(path)
{
    var rc = fileparse(path);
    return(rc[2]);
}

// name: writename
// desc: takes a filename (with path) and id of element to write
// basename into.
// notes: This only does it on windows browsers and IE.
function writename(filepath, id)
{
	var isWindows = (navigator.platform.indexOf("Win") >= 0);
	var isMoz     = (navigator.userAgent.indexOf("Gecko") > -1);
	var isSaf     = (navigator.userAgent.indexOf("Safari") > -1);

	// don't do on safari
	if (isSaf) 
		return;

	// only do write on windows or mozilla browser (safari pretends to be Gecko browser)
	if ((!isWindows) && (!isMoz)) 
		return;

	// attempt to do this magic, just ignore if failed 
	try {
		document.getElementById(id).innerHTML = "&nbsp;" + basename(filepath);
	} catch (e) {
		// it would be nice to console log something but
		// not possible right now.
	}

	return;
}

function fixCaption() {
	//the combination of the toggleView function and 
	// the setActiveStyleSheet function in styleSwitcher.js
	// causes Firefox to stop cascading the font size of a 
	// table element into the table's caption element.
	// This function fixes the caption font size to 70% 
	// (roughly equal to .8 x .87 which are the sizes in 
	// text and caption rules)
	if ((navigator.userAgent.indexOf("Firefox")!=-1) && (navigator.userAgent.indexOf("Firefox/3")==-1)) {
	try {
		document.getElementById('cap').style.fontSize="70%";
	} catch (e) {
	}
	}
}

function confirmAction(message) {
	try {
		if (confirm(message)) {
		return true;
	}
	return false;
	} catch (e) {
	}
}

function openClipboard() {
	var cb = window.open('', 'ViewClipboard', 'height=550,width=800,resizable,scrollbars,status');
	cb.focus();
}

function checkClipboard(clipboard) {
	//validate clipboard for missing names, duplicate names etc.
	var seen = new Array();
	var txt_missing = "Clipboard items must have file names.";
	var txt_duplicate = "Clipboard items must have unique names."
	var count = document.getElementById("cbd_count").value;

	if (document.getElementById("txt_missing"))
		txt_missing = document.getElementById("txt_missing").value;
	if (document.getElementById("txt_duplicate"))
		txt_duplicate = document.getElementById("txt_duplicate").value;

	for (var i = 0; i < count; i++) {
        if (!document.getElementById("checkbox"+i).checked) {
    		if (document.getElementById("new_file"+i).value == "") {
	    		//missing a filename
		    	alert(txt_missing);
    			clipboard = 0;
	    		break;
    		}

	    	//combine path and name
    		var new_name = document.getElementById("new_path"+i).value + "/" + document.getElementById("new_file"+i).value
	    	//convert any double slashes (//) to a single slash (/)
    		new_name.replace(/\/\//g,"/"); 
    		if (seen[new_name]) {
    			//clipboard contains duplicate new_name
    			alert(txt_duplicate);
	    		clipboard = 0;
		    	break;
    		} else {
	    		//not seen this new_name before
		    	seen[new_name] = 1;
    		}
        }
	}
	
	if (clipboard) {
		clipboard.submit();
	}
}

function resetClipboard() {
	//reset the clipboard form properly even if it is re-displaying rejected update data
	var count = document.getElementById("cbd_count").value;

	for (var i = 0; i < count; i++) {
		var file_name = fileparse(document.getElementById("file_name"+i).value, 1);
        var file_path = file_name[1];
        if (!file_path) {
            file_path = ""
        }
        document.getElementById("new_path"+i).value = file_path;
		document.getElementById("new_file"+i).value = file_name[2];
		document.getElementById("checkbox"+i).checked = 0;
	}
}

function updClipboard(count,text,dupes) {
	//update dynamic data in create package and set appropriate required styles
	try {
		//update file count
		document.getElementById("cbd_count").value = count;
		document.getElementById("cbd_dupes").value = dupes;
		document.getElementById("varData").innerHTML = ""; //This makes IE 5.1+ on Mac behave!
		document.getElementById("varData").innerHTML = text + "&nbsp;";

		//update required files
		if (count == 0) {
			//cliboard is empty so must make file1 required again
			document.getElementById("file1_prefix").innerHTML = ""; //This makes IE 5.1+ on Mac behave!
			document.getElementById("file1_prefix").innerHTML = "*";
			document.getElementById("file1_td").className = "fRequired";
		}
		
		//enable send button
		if (dupes == 0) {
			if (!dest_reqs_jtk || document.getElementById("jt").value == openedjtk || document.getElementById("jt").value == 1) {
				enableSendButton();
			}
			document.getElementById("cpd_dupe_msg").className = "small hide";
		} else {
			disableSendButton();
			document.getElementById("cpd_dupe_msg").className = "small";
		}
	} catch (e) {
	}
}

function processBroadcast(check) {
   //when a dock checkbox is clicked this will look for other broadcast packages and sync their checkboxes
   var trkid = document.getElementById("checkbox"+check).value;
   var pkgid = trkid.substr(0,trkid.indexOf("."));
   var select = document.getElementById("checkbox"+check).checked;
   
   for (var i = 0; true; i++) {
        if (!document.getElementById("checkbox"+i)) {
            return;
        }
        
        if (pkgid && (document.getElementById("checkbox"+i).value.indexOf(pkgid) == 0)) {
        	//found a duplicate package id (from a broadcast) so sync its checkbox
        	document.getElementById("checkbox"+i).checked = select;
        }
   }
}  


//Next 2 functions expand the show/hide capability from form tips to additional items (row, cell, block) also.
//Copied from Service Portal's spFunctions.js
function replaceBlock(objStyle, className) {
	//Can't use this for showing/hiding iframe content as IE Mac can't handle it properly
	try {
		if (objStyle.cssRules) {
			var r = objStyle.cssRules;
		} else {
			var r = objStyle.rules;
		}

		for ( var i = 0; i < r.length; i++ ) {
			if( r[i].selectorText == className || r[i].selectorText == '*' + className) { 
				try {
					r[i].style.display = (r[i].style.display == 'none') ? 'block' : 'none';
				} catch (e) {
					// IE Windows doesn't do table-cell!
					r[i].style.display = (r[i].style.display == 'none') ? 'block' : 'none';
				}
				return(true);
			}
		}
	} catch (e) {
		return(false);
	}
}

function toggleView(className,replaceType) {
	try {
		if(replaceType=="row") {
			cssSwitch = replaceRows(document.styleSheets[2], '.' + className);
		} else if(replaceType=="cell") {
			cssSwitch = replaceCells(document.styleSheets[2], '.' + className);
		} else if(replaceType=="block") {
			cssSwitch = replaceBlock(document.styleSheets[2], '.' + className);
		}
		
		//Nudge window to force browser to re-render. Using resizeBy is buggy in some browsers - the window origin can be reset too!
		window.scrollBy(0,1);
		window.scrollBy(0,-1);
		
		//Use cssSwitch to detect an error in changing the display property and so default to show item
		if(document.getElementById(className + 'Off').style.display=="none" || !cssSwitch) {
			document.getElementById(className + 'Off').style.display="inline";
			document.getElementById(className + 'On').style.display="none";
		} else {
			document.getElementById(className + 'Off').style.display="none";
			document.getElementById(className + 'On').style.display="inline";
		}
	} catch (e) {
	}
}
