﻿// Detect if the browser is IE or not.
// If it is not IE, we assume that the browser is NS.
var IE = document.all?true:false;

// If NS -- that is, !IE -- then set up for mouse capture
if (!IE) document.captureEvents(Event.MOUSEMOVE);

var mousePosition = {};
mousePosition.x = 0;
mousePosition.y = 0;
	
if (!this.Util) {
    Util = {};
}

Util.AjaxRequest = function(reqeustMethod, parameters, callbackFn) {

    var returnedObject;
	var f = $("#form");
	var action = f.attr("action")+'&action='+reqeustMethod;

    if (!parameters) {
        parameters = {};
    }

    if (callbackFn) {
	    $.ajax({
	        url: action,
	        cache: false,
	        data: parameters,
	        type: 'POST',
	        success: function(data) {
	    		callbackFn(data);
	        }
	    });

    } else {
	    $.ajax({
	        url: action,
	        dataType: 'json',
	        cache: false,
	        async: false,
	        type: 'POST',
	        data: parameters,
	        success: function(json) {
	            returnedObject = json;
	        }
	    });
    }
    
    return returnedObject;
};

Util.AjaxPost = function(reqeustMethod, callbackFn) {
	var returnedObject;
	var f = $("#form");
	var action = f.attr("action")+'&action='+reqeustMethod;
	//$("#action").value = requestMethod;
	var serialized = f.serialize();
	
	$.ajax({  
		url: action,  
		data: serialized,
		cache: false,
		type: 'POST',
        success: function(data){  
             if (data.success)
            	 callbackFn(data);  
             else  
            	 callbackFn(data);  
         }
	});  
};

Util.FocusControl = function (ctl)
{
    var id = ctl.id;
    setTimeout(function () { 
            var ctl = document.getElementById(id);
            if (ctl != null) {
                if (ctl.disabled == false) {
                    try {
                        // Force, force, force IE to set focus to the requested control.
                        ctl.focus(); 
                        ctl.focus(); 
                        ctl.focus(); 
                    } catch (ex) {
                        alert(ctl.id + " could not get focus.");
                    }
                }
            }
        }, 350);
};

Util.AskDelete = function () {
	return confirm("Press Ok to confirm delete.\n\nThis operation can not be undone.");
};

Util.DisplayError = function(message) {
	
	alert(message);
	
};

Util.SelectDropDownValue = function (dropdown, value) {
	for( var i=0; i<dropdown.options.length; i++){
		dropdown.options[i].selected=(dropdown.options[i].value==value);
	}	
};

Util.ConfirmTrash = function () {
	return confirm("Are you sure you want to Trash this item?");
};

Util.GatherForm = function () {
	
	var inputs = document.getElementsByTagName('input');
	var textareas = document.getElementsByTagName('textarea');
	var selects = document.getElementsByTagName('select');
	
	var params = {};
	

	return { location_id: ScheduleForm.locationsDD.value };
	
};

Util.getElementsByClassName = function (className) {

	if (IE) {
		var foundArray = new Array();
		var eleAry = document.getElementsByTagName('*');
		for (i=0;i<eleAry.length;i++) {
			if (eleAry[i].className == className) {
				foundArray.push(eleAry[i]);
			}
		}
		return foundArray;
	} else {
		return document.getElementsByClassName(className);
	}

};

Util.GetMousePosition = function (e) {

	if (IE) { // grab the x-y pos.s if browser is IE
	    tempX = event.clientX + document.body.scrollLeft;
	    tempY = event.clientY + document.body.scrollTop;
	} else {  // grab the x-y pos.s if browser is NS
	    tempX = e.pageX;
	    tempY = e.pageY;
	}  
	// catch possible negative values in NS4
	if (tempX < 0){tempX = 0}
	if (tempY < 0){tempY = 0} 
	// show the position values in the form named Show
	// in the text fields named MouseX and MouseY
	mousePosition.x = tempX;
	mousePosition.y = tempY;
	
	return true;
};

Util.GetObjectPosition = function (obj) {

		var curleft = curtop = 0;
		if (obj.offsetParent) {
			do {
				curleft += obj.offsetLeft;
				curtop += obj.offsetTop;
			} while (obj = obj.offsetParent);
			return [curleft,curtop];
		}
};

Util.ClearElement = function (elementId) {

	if ( elementId.hasChildNodes() )
	{
	    while ( elementId.childNodes.length >= 1 )
	    {
	    	elementId.removeChild( elementId.firstChild );       
	    } 
	}

};

Util.htmlspecialchars = function  (string, quote_style, charset, double_encode) {
    // Convert special characters to HTML entities  
    // 
    // version: 1008.1718
    // discuss at: http://phpjs.org/functions/htmlspecialchars    // +   original by: Mirek Slugen
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Nathan
    // +   bugfixed by: Arno
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Ratheous
    // +      input by: Mailfaker (http://www.weedem.fr/)
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +      input by: felix    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // %        note 1: charset argument not supported
    // *     example 1: htmlspecialchars("<a href='test'>Test</a>", 'ENT_QUOTES');
    // *     returns 1: '&lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;'
    // *     example 2: htmlspecialchars("ab\"c'd", ['ENT_NOQUOTES', 'ENT_QUOTES']);    // *     returns 2: 'ab"c&#039;d'
    // *     example 3: htmlspecialchars("my "&entity;" is still here", null, null, false);
    // *     returns 3: 'my &quot;&entity;&quot; is still here'
    var optTemp = 0, i = 0, noquotes= false;
    if (typeof quote_style === 'undefined' || quote_style === null) {        quote_style = 2;
    }
    string = string.toString();
    if (double_encode !== false) { // Put this first to avoid double-encoding
        string = string.replace(/&/g, '&amp;');    }
    string = string.replace(/</g, '&lt;').replace(/>/g, '&gt;');
 
    var OPTS = {
        'ENT_NOQUOTES': 0,        'ENT_HTML_QUOTE_SINGLE' : 1,
        'ENT_HTML_QUOTE_DOUBLE' : 2,
        'ENT_COMPAT': 2,
        'ENT_QUOTES': 3,
        'ENT_IGNORE' : 4    };
    if (quote_style === 0) {
        noquotes = true;
    }
    if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags        quote_style = [].concat(quote_style);
        for (i=0; i < quote_style.length; i++) {
            // Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4
            if (OPTS[quote_style[i]] === 0) {
                noquotes = true;            }
            else if (OPTS[quote_style[i]]) {
                optTemp = optTemp | OPTS[quote_style[i]];
            }
        }        quote_style = optTemp;
    }
    if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
        string = string.replace(/'/g, '&#039;');
    }    if (!noquotes) {
        string = string.replace(/"/g, '&quot;');
    }
 
    return string;
};

Util.generatePageIdentifier = function(inputCtl, outputCtl) {
	var pageIdentifierTextBox = document.getElementById(outputCtl);

	var identifer = inputCtl.value;
	identifer = identifer.toLowerCase().trim();
	identifer = identifer.replace(/ /g, '-');
	identifer = identifer.replace(/&/g, 'and');
	identifer = identifer.replace(/[^-a-zA-Z 0-9]+/g,'');
	
	pageIdentifierTextBox.value = identifer;
},

Util.GenerateGUID = function () {
	
   return (Util.S4()+Util.S4()+"-"+Util.S4()+"-"+Util.S4()+"-"+Util.S4()+"-"+Util.S4()+Util.S4()+Util.S4());

};

Util.S4 = function () {
   return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};

// Function prototypes to make up for functions that IE neglects to support. 

String.prototype.trim = function() { 
    return this.replace(/^\s+|\s+$/g,''); 
}; 

String.prototype.startsWith = function(t, i) {
    if (i == false) {
        return
        (t == this.substring(0, t.length));
    } else {
        return (t.toLowerCase() == this.substring(0, t.length).toLowerCase());
    } 
};

String.prototype.endsWith = function(t, i) {
    if (i == false) {
        return (t
== this.substring(this.length - t.length));
    } else {
        return
        (t.toLowerCase() == this.substring(this.length -
t.length).toLowerCase());
    } 
};

Array.prototype.remove = function(from, to) {
	  var rest = this.slice((to || from) + 1 || this.length);
	  this.length = from < 0 ? this.length + from : from;
	  return this.push.apply(this, rest);
};

