$(document).ready(ecl_init_global_func);

function ecl_init_global_func()
{
    // Prevent double submit
    prevent_double_submit();
    
    init_showHide();
    
    init_selectAllCheckbox();
}



var WEB_PARAM = "$param$";
function splitParams(params) { return params.split(WEB_PARAM); }
function getParam(params, ix)
{
    if (params.length > ix)
    {
        return params[ix]; 
    }
    else
    {
        return "";
    }
}

function removeErrors() {
    $(".errors").slideUp("fast", function(){$(this).remove();});
    $(".error").removeClass("error");
}

function parseDate(textdate) {
	var myArray = textdate.split('-');
	var input = myArray[1] + ' ' + myArray[0] + ', ' + takeYearWithYear(parseInt(myArray[2],10));
	var output = Date.parse(input);
	return new Date(output)
}

function parseMonth(monthIndex) {
    var monthStr = "";
    switch (monthIndex) {
        case 0: monthStr = 'Jan'; break;
        case 1: monthStr = 'Feb'; break;
        case 2: monthStr = 'Mar'; break;
        case 3: monthStr = 'Apr'; break;
        case 4: monthStr = 'May'; break;
        case 5: monthStr = 'Jun'; break;
        case 6: monthStr = 'Jul'; break;
        case 7: monthStr = 'Aug'; break;
        case 8: monthStr = 'Sep'; break;
        case 9: monthStr = 'Oct'; break;
        case 10: monthStr = 'Nov'; break;
        case 11: monthStr = 'Dec'; break;
    }
    return monthStr;
}

function takeYear(theDate) {
    x = theDate.getYear();
    var y = x % 100;
    y += (y < 38) ? 2000 : 1900;
    return y;
}

function takeShortYear(theDate) {
    x = theDate.getYear();
    x = (x % 100);
    if (x < 10){
        return "0"+x;
    }
    return x;
}

function takeYearWithYear(y) {
    y += (y < 38) ? 2000 : 1900;
    return y;
}

function replaceZeros(value) {

	return value.replace(/^[0]+/g,"");
}

/* ########################################################################### *
/* ##### PREVENT DOUBLE SUBMISSION
/* ########################################################################### */

function prevent_double_submit() {
    $('form').submit(function() {
        $(this).find("button").click(function() {
            return false;
        });
    });
}

var dom = document.getElementById ? true:false;
var nn4 = document.layers ? true:false;
var ie4 = document.all ? true:false;
var ie=document.all;

function getObject(id)
{
 if (dom) return document.getElementById(id);
 if (ie4) return document.all[id];
 if (nn4) return document.layers[id];
}

function setTop(id,val){
	if(dom)
		getObject(id).style.top = val+"px";
	else if(ie4)
	    getObject(id).style.pixelTop = val+"px";
	else if(nn4)
	    getObject(id).top = val;	
}

function setLeft(id,val){
	if(dom)
	    getObject(id).style.left = val+"px";
	else if(ie4)
	    getObject(id).style.pixelLeft = val+"px";
	else if(nn4)
	    getObject(id).top = val;	
}

function setVisibility(id,val)
{
	if(dom)
	    getObject(id).style.visibility = val;
    else if(ie4)
        getObject(id).style.visibility = val;
	else if(nn4)
	    getObject(id).visibility = val;	
}

function opacity(id, opacStart, opacEnd, millisec) {
	//speed for each frame
	var speed = Math.round(millisec / 100);
	var timer = 0;

	//determine the direction for the blending, if start and end are the same nothing happens
	if(opacStart > opacEnd) {
		for(i = opacStart; i >= opacEnd; i--) {
			setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
			timer++;
		}
	} else if(opacStart < opacEnd) {
		for(i = opacStart; i <= opacEnd; i++)
			{
			setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
			timer++;
		}
	}
}
//change the opacity for different browsers
function changeOpac(opacity, id) {
	var object = document.getElementById(id).style; 
	object.opacity = (opacity / 100);
	object.MozOpacity = (opacity / 100);
	object.KhtmlOpacity = (opacity / 100);
	object.filter = "alpha(opacity=" + opacity + ")";
}

function changeOpacByObject(opacity, obj) {

	var object = obj.style; 
	object.opacity = (opacity / 100);
	object.MozOpacity = (opacity / 100);
	object.KhtmlOpacity = (opacity / 100);
	object.filter = "alpha(opacity=" + opacity + ")";
}

function shiftOpacity(id, millisec) {
	//if an element is invisible, make it visible, else make it ivisible
	if(document.getElementById(id).style.opacity == 0) {
		opacity(id, 0, 100, millisec);
	} else {
		opacity(id, 100, 0, millisec);
	}
}

function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

/**
 * Generic show/hide code.
 * <br/>
 * To use this code you need to:
 * - Add the "showHideSource" class to the input that will control what is shown
 * - OR: Add "parentShowHideSource" to the surrounding div, with "showHideValue_$lt;value&gt; for the value of the input
 *   to add the showHideSource too. Useful for a list of checkboxes where you only want the action for one.
 * - OPTIONAL: Add "showHideName" if you want to use the elements name instead of id for matching
 * - If you want to use the text instead of the value for the show hide, add "showHideText" class to input
 * - Add a one of the following classes to the page sections to be shown/hidden
 *   - &lt;id&gt;-hide if this section should be hidden by default
 *   - &lt;id&gt;-show if this section should be shown by default
 * - Add a class of the format &lt;id&gt;_&lt;value&gt; to dictate which value this section should be shown/hidden for.
 *   Accepts multiple values if the section should be shown/hidden for more than one selection
 *   
 * @return
 */
function init_showHide() {
	$('.parentShowHideSource').each(function(){
		var classes = $(this).attr('class').split(/\s+/);
		for (i = 0; i < classes.length; i++) {
			var clazz = classes[i];
			if (clazz.substring(0, 14) == "showHideValue_") {
				var value = clazz.substring(14);
				$(this).find('[value="' + value + '"]').each(function(){
					$(this).addClass('showHideSource');
					$(this).addClass('showHideName');
				});
			}
		}
	});
	
	$('.showHideSource').each(function(){
		// For each show hide we need to:
		var id = $(this).attr('id');
		
		if ($(this).hasClass('showHideName')) {
			id = $(this).attr('name').replace(".", "_");
		}
		
		// Setup on-click event
		$(this).change(function(){
			// If this is a checkbox, only add the value if we are checked
			var valueClass = '';
			if ($(this).attr('type') == 'checkbox')
			{
				if ($(this).attr('checked'))
				{
					valueClass = id + "_" + $(this).val();
				}
				else
				{
					valueClass = id + "_";
				}
			}
			else
			{
				if ($(this).hasClass("showHideText"))
				{
					valueClass = id + "_" + $(this).children("option:selected").text();
				}
				else
				{
					valueClass = id + "_" + $(this).val();
				}
			}
			$('.' + id + '-hide').each(function(){
				if ($(this).hasClass(valueClass))
				{
					$(this).show();
				}
				else
				{
					$(this).hide();
				}
			});
			
			$('.' + id + '-show').each(function(){
				if ($(this).hasClass(valueClass))
				{
					$(this).hide();
				}
				else
				{
					$(this).show();
				}
			});
		});
		
		// Show/hide the relevant page section
		$(this).change();
	});
}

function init_selectAllCheckbox(){
	// Select all checkboxes
    $("input[type='checkbox'].selectAll").each(function(){
    	var id = $(this).attr('id');
    	
    	$('.' + id).click(function() {
    		var allChecked = true;
    		$("input[type='checkbox']." + id).each( function() {
    			allChecked &= this.checked;
    		});

    		if (allChecked) {
    			$("#" + id).attr("checked", "checked");
    		} else {
    			$("#" + id).attr("checked", "");
    		}
    	});
    	
    	var initAllChecked = true;
		$("input[type='checkbox']." + id).each( function() {
			initAllChecked &= this.checked;
		});
		if (initAllChecked) {
			$(this).attr("checked", "checked");
		} else {
			$(this).attr("checked", "");
		}
    	
	    $(this).click( function() {
			
			if ($(this).attr("checked")) {
				$('.' + id).each( function() {
					this.checked = true;
				});
			} else {
				$('.' + id).each( function() {
					this.checked = false;
				});
			}
		});
    });
}
