/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/* This file is for static Javascript functions. There may be more in the
 * application file if they need to be written dynamically. */

function popVT(url) { vt = window.open(url,'vt',"width=700,height=600,scrollbars=no,resizable=yes"); }
function popCopy(url) { vt = window.open(url,'copy',"width=700,height=600,scrollbars=yes,resizable=yes"); }
function popCal(url) { cal = window.open(url,'cal','width=700,height=400,scrollbars=no,resizable=yes'); }

/* Text counter functions */

function getCounterElement(obj) {

    id = obj.name+'_count';

    if(!document.getElementById(id)) {
        var elem = document.createElement('div');
        elem.setAttribute('id', id); 
        elem.setAttribute('class', 'textCounter'); 
        elem.className = 'textCounter';
        elem.appendChild(document.createTextNode(''));
        obj.parentNode.appendChild(elem);
    }
    return document.getElementById(id);
}

var text_obj = null;
var feed_obj = null;
var counter_lag = 50;

function textCounter(obj, maxlength) {
    text_obj = obj;
    func = 'textCounterWithLag('+maxlength+')';
	eval(func); // Now
    window.setTimeout(func, counter_lag); // Later
}

function textCounterWithLag(maxlength) {
    var elem = getCounterElement(text_obj);
    var len = getFieldLength(text_obj);
    var text = document.createTextNode(len + "/" + maxlength);
    elem.style.backgroundColor = (maxlength < len) ? '#dd9999' : '#ffffff';
    elem.replaceChild(text, elem.childNodes[0]);
}

function feedbackCounter(obj, maxlength, over_class, normal_class) {
    feed_obj = obj;
    func = 'feedbackCounterWithLag('+maxlength+',"'+over_class+'","'+normal_class+'")';
	eval(func); // Now
    window.setTimeout(func, counter_lag); // Later
}

function feedbackCounterWithLag(maxlength, over_class, normal_class) {
    aclass = (maxlength < getFieldLength(feed_obj) ? over_class : normal_class);
    // feed_obj.className = aclass;
    if(maxlength < getFieldLength(feed_obj)) {
        feed_obj.style.borderColor = '#dd3333';
    }
    else {
        feed_obj.style.borderColor = '#aaaaaa';
    }
}

function getFieldLength(obj) {
    return obj.value.replace(/\n/gm, '').length; // Not newlines
}

/* Admin helpers */

function delete_client_confirmation(label) {
    return 'You are about to delete the client " + label + ". In the interests of safety, this will not be allowed unless you delete or re-categorise any jobs belonging to this client.\n \'OK\' to delete, \'Cancel\' to stop.'
}

function delete_job_confirmation() {
    return 'You are about to delete a job. In the interests of safety, this will not be allowed unless you also delete or re-categorise all tours and images belonging to this job first. This action is also irreversible.\n \'OK\' to delete, \'Cancel\' to stop.'
}

function delete_region_confirmation() {
    return 'You are about to delete a region. This may have an effect on permissions for external users (they may lose access to jobs in this region). This action is irreversible.\n \'OK\' to delete, \'Cancel\' to stop.'
}

function delete_gallery_confirmation() {
    return 'You are about to delete a gallery. This process will also delete the entire folder in which the images are stored for this gallery. Proceed with caution!'
}

function delete_version_confirmation() {
    return 'You are about to completely delete an image version. This should really only be done to remove data entry errors.\n \'OK\' to delete, \'Cancel\' to stop.'
}

function delete_template_confirmation() {
    return 'If you remove this template you will lose any current or past copy stored in it for this job.\n \'OK\' to delete, \'Cancel\' to stop.'
}

function delete_image_confirmation() {
    return 'You are about to delete a proofing image. This also deletes the correspondance relating to this image. This action is irreversible.\n \'OK\' to delete, \'Cancel\' to stop.'
}

/* Requires a specific context */
function update_cal(task) {
    var params = Form.serialize($('delegation_form'));
    new Ajax.Updater('t_'+task, '../admin/jobs/_task_delegate.php', {asynchronous:true, parameters:params});
    Dialog.closeInfo()
}

function initStates(statesstr) {
	VisibleStates = statesstr.split(',');
}

function initZones(zonesstr) {
	VisibleZones = zonesstr.split(',');
}

function initCalendarColumns(displaycols,dohide) {
	/* Set a global variable defining column names */
	CalColumnNames = new Array("status","time","label","staff_comments","vp","photo","copy","digital_media","video","editing","client","agent","region");
	/* split the displaycols string by comma, then set corresponding visible cols to true */
	var displayColArray = displaycols.split(',');
	/* Set a global variable defining the visible columns */
	VisibleCalColumns = new Array ();
	// safari loops over shadow object constructors, so we can't use for (..in..)
	for (var i=0; i <= 13; i++) if (!(VisibleCalColumns[i] = in_array(CalColumnNames[i],displayColArray)) && dohide) { hideCol(i,CalColumnNames[i])};
}
function calendarChangeDay(loc) {
    window.location.href=loc+displayFilterString();
    return false;
}

function calendarSpreadsheet(loc) {
	// remove any previous display arguments
	var newloc = removeDisplayFilterString(loc);
	window.location.href=newloc+displayFilterString();
	return false;
}

function removeDisplayFilterString(loc) {
	return loc.replace(/&display=[^&]*/,"")
	          .replace(/&selected_zones[^=]*=[^&]*/,"")
	          .replace(/&selected_states[^=]*=[^&]*/,"");
}

function displayFilterString() {
	var str = '&selected_states='+VisibleStatesToStr() + 
	         '&selected_zones='+VisibleZonesToStr() + 
	         '&display='+VisibleColsToStr();
	return str;
}
function VisibleColsToStr () {
	var colstr = '';
	for (var i=0; i <= 13; i++) if (VisibleCalColumns[i]) colstr += CalColumnNames[i]+',';
	return colstr;
}
function VisibleStatesToStr() {
	return VisibleStates.join(',');
}
function VisibleZonesToStr() {
	return VisibleZones.join(',');
}
/* calendar functions */
function hideCol(col_no, col_name) {
	show_hide_col('cal_dayreport',col_no,false);
	var sel = document.getElementById('showcol');
	appendOption(sel,col_no,col_name);
	return false;
}

function showCol() {
	var sel = document.getElementById('showcol');
	col_no = sel.options[sel.selectedIndex].value;
	if (col_no == 'all') {
		var i;
		while (sel.options.length > 3) {
			show_hide_col('cal_dayreport',sel.options[3].value,true);
			sel.remove(3);
		}
	}
	else if (col_no != ''){
		show_hide_col('cal_dayreport',col_no,true);
		sel.remove(sel.selectedIndex);
	}
	sel.selectedIndex = 0;

	return false;
}
function show_hide_col(table_name,col_no,doShow) {
	var stl;
	stl = (doShow) ? '' : 'hidden';
	
	VisibleCalColumns[col_no] = doShow;

	var tbl  = document.getElementById('cal_dayreport');
	var rows = tbl.getElementsByTagName('tr');
	
	var cels = rows[0].getElementsByTagName('th');
	changeClass(cels[col_no],stl);

	for (var row=1; row<rows.length;row++) {
		var cels = rows[row].getElementsByTagName('td');
		changeClass(cels[col_no],stl);
	}
}
function appendOption(elSel,optionvalue,optionname)
{
  var elOptNew = document.createElement('option');
  elOptNew.text = optionname;
  elOptNew.value = optionvalue;

  try {
    elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
  }
  catch(ex) {
    elSel.add(elOptNew); // IE only
  }
}
function changeClass (element, newClass) {
	//var element = document.getElementById(elementID);

	if (typeof element != "undefined") {
		element.setAttribute("class", newClass); //For Most Browsers
		element.setAttribute("className", newClass); //For IE; harmless to other browsers.
	}
}
function in_array (needle, haystack) {
		var found = false;
	
        for (key in haystack) {
	        if (haystack[key] == needle) {
	             found = true;
	             break;
		    }
	    }                                                                
		return found;
}
