// @@  @@    @@               @            
// @@  @@                    @@            
// @@  @@   @@@     @@@@@   @@@@@   @@@@   
// @@  @@    @@    @@        @@        @@  
// @@  @@    @@     @@@@     @@     @@@@@  
//  @@@@     @@        @@    @@ @  @@  @@  
//   @@     @@@@   @@@@@      @@    @@@ @@ 

// VISTA common scripts.

// Copyright (c) 2005 Rainow Systems.
// Designed and coded by Rob Nicholson.

// VistaTrapCR: Trap user pressing CR.

function VistaTrapCR() {
	if (event.keyCode == 13) {
        event.returnValue = false;
		event.cancel = true;
	}
}
                                        
// vs_InitPopup: Initialise the popup window.

function vs_InitPopup(Visible) {
	var PopupDialog = document.getElementById(PopupDivID);
	if (PopupDialog != null) {
	    var s = PopupDialog.style;
	    if (Visible)
	        s.visibility = 'visible';
	    else
	        s.visibility = 'hidden';
	    s.left = PopupX+'px';
	    s.top = PopupY+'px';
	}
}

// String splicing.
	
function VistaLTrim(text) {
    return text.replace( /^\s*/, "" )
}

function VistaRTrim(text) {
    return text.replace( /\s*$/, "" )
}

function VistaTrim(text) {
    return VistaLTrim(VistaRTrim(text))
}

function VistaLeft(str, n) {
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}

function VistaRight(str, n) {
    if (n <= 0)
        return "";
    else if (n > String(str).length)
        return str;
    else {
		var iLen = String(str).length;
		return String(str).substring(iLen, iLen - n);
	}
}

// vs_CellEvent object: defines which grids and columns should cause postback when changed.

function vs_CellEvent(GridName, ColumnKey)
	{
	this.GridName = GridName;
	this.GridNameLength = GridName.length;
	this.ColumnKey= ColumnKey;
	}

// Initialise VistaCellEvents array.
	
var vs_CellEvents = new Array();

// vs_GridAfterCellUpdateHandler: Causes a postback if the grid and cell
// causing the event are in the vs_CellEvents array.

function vs_GridAfterCellUpdateHandler(gridName, cellId)
	{
	
	// Get the cell object.
	
	var Cell = igtbl_getCellById(cellId);
	var Column = Cell.Column;
	
	// See if event should be handled. If so, cause postback.
	
	for (i in vs_CellEvents)
		{
		var Event = vs_CellEvents[i];
		var Name = VistaApp.Right(gridName, Event.GridNameLength);
		if (Name == Event.GridName && Column.Key == Event.ColumnKey)
			{
			igtbl_needPostBack(gridName);
			break;
			}
		}
	}

// vs_GridPostBack: Cause grid postback.

function vs_GridPostBack(GridName)
	{
	igtbl_needPostBack(GridName);
	}

// vs_HideControls; Hides drop down lists

function vs_HideControls() {
	
	for (var i in document.all) {
		var node = document.all[i];

		if (node.type == 'select-one') {
			var style = node.style;
			node.setAttribute('prev_style_visibility', style.visibility);
			style.visibility = 'hidden';
		}
	}
}


// vs_ShowControls; Returns drop down lists to previous state

function vs_ShowControls() {

	for (var i in document.all) {
		var node = document.all[i];

		if (node.type == 'select-one') {
			var style = node.style;
			var visibility = node.getAttribute('prev_style_visibility');
			if (visibility != null) {
				style.visibility = visibility;
			}
		}
	}
}

// vs_HTML_ToTextArea: Prepare a string of use in the textarea tag.

function vs_HTML_ToTextArea(Text)
    {
    var OldText;
    do
        {
        OldText = Text;
        Text = Text.replace('<br>','\r\n');
        }
    while (OldText != Text);
    return (Text);
    }
    
// vs_TextArea_ToHTML: Convert back from textarea to HTML.

function vs_TextAreaToHTML(Text)
    {
    var OldText;
    do {
        OldText = Text;
        Text = Text.replace('\r\n','<br>');
    }
    while (OldText != Text);
    return (Text);
    }

// WordCount: Count number of words.

function VistaWordCount(Field)
    {
    var char_count = Field.value.length;
    var fullStr = Field.value + " ";
    var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;
    var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, "");
    var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi;
    var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " ");
    var splitString = cleanedStr.split(" ");
    var word_count = splitString.length -1;
    if (fullStr.length <2)
        word_count = 0;
    if (word_count == 1)
        wordOrWords = " word";
    else
        wordOrWords = " words";
    return word_count+wordOrWords;
}

// Vista constructor.

function Vista() {
    this.QueryString = new VistaQueryString();
    this.GUID = this.QueryString.Get("GUID","");
    this.SetVariable = VistaSetVariable;
    this.GetVariable = VistaGetVariable;
    this.VariableExists = VistaVariableExists;
    this.GetExpDate = VistaGetExpDate;
    this.GetCookieVal = VistaGetCookieVal;
    this.GetCookie = VistaGetCookie;
    this.SetCookie = VistaSetCookie;
    this.DeleteCookie = VistaDeleteCookie;
    this.MapTypeToString = VistaMapTypeToString;
    this.MapTypeFromString = VistaMapTypeFromString;
    this.Startup = VistaStartup;
    this.DoPostBack = VistaDoPostBack;
    this.LTrim = VistaLTrim;
    this.RTrim = VistaRTrim;
    this.Trim = VistaTrim;
    this.Left = VistaLeft;
    this.Right = VistaRight;
    this.WordCount = VistaWordCount;
    this.VistaGridRowSelected = VistaGridRowSelected;
    this.TrapCR = VistaTrapCR;
}

// DoPostBack: Perform Vista custom logic on postback.

function VistaDoPostBack(eventTarget, eventArgument) {

    // Carry out autocomplete manually.
    
    if (document.all) {
        var TheForm = document.forms['aspnetForm'];
        if (!TheForm)
            TheForm = document.aspnetForm;
        window.external.AutoCompleteSaveForm(TheForm);
    }
    
    // Perform original postback.
    
    __doPostBack = VistaApp.OriginalDoPostBack;
    __doPostBack(eventTarget, eventArgument);
}

// Startup: Called after body has loaded.

function VistaStartup() {

    // Patch in Vista DoPostBack routine (for autocomplete)
    
    this.OriginalDoPostBack = __doPostBack;
    __doPostBack = this.DoPostBack;

}

// SetVariable: Set a variable via cookies.
    
function VistaSetVariable(Name, Value) {
    var Expires = this.GetExpDate(0, 2, 0);
    this.SetCookie(this.GUID + Name, Value, Expires)
    }

// GetVariable: Get a variable via cookies.
    
function VistaGetVariable(Name, DefaultValue) {
    var Value = this.GetCookie(this.GUID + Name);
    return (Value != null) ? Value : DefaultValue;
    }

// VariableExists: Check if a variable exists.

function VistaVariableExists(Name) {
    return this.GetCookie(this.GUID + Name) != null;
    }

function VistaQueryString(qs) { // optionally pass a querystring to parse
	this.params = {};
	this.Get=VistaQueryStringGet;
	this.Exists=VistaQueryStringExists;
	if (qs == null);
		qs=location.search.substring(1,location.search.length);
	if (qs.length == 0) 
		return;
    // Turn <plus> back to <space>
    // See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ');
	var args = qs.split('&'); // parse out name/value pairs separated via &

    // split out each name=value pair
	
	for (var i=0;i<args.length;i++) {
		var pair = args[i].split('=');
		var name = unescape(pair[0]);
		var value = (pair.length==2)
			? unescape(pair[1])
			: name;
		
		this.params[name] = value;
	    }
    }

function VistaQueryStringGet(key, defaultvalue) {
	var value=this.params[key];
	return (value!=null) ? value : defaultvalue;
    }
    
function VistaQueryStringExists(Key) {
    var Value = this.params[Key];
    return Value != null;
    }

// utility function to retrieve an expiration date in proper
// format; pass three integer parameters for the number of days, hours,
// and minutes from now you want the cookie to expire (or negative
// values for a past date); all three parameters are required,
// so use zeros where appropriate
function VistaGetExpDate(days, hours, minutes) {
    var expDate = new Date();
    if (typeof days == "number" && typeof hours == "number" && typeof hours == "number") {
        expDate.setDate(expDate.getDate() + parseInt(days));
        expDate.setHours(expDate.getHours() + parseInt(hours));
        expDate.setMinutes(expDate.getMinutes() + parseInt(minutes));
        return expDate.toGMTString();
    }
}
    
// utility function called by vs_GetCookie( )
function VistaGetCookieVal(offset) {
    var endstr = document.cookie.indexOf(";", offset);
    if (endstr == -1) {
        endstr = document.cookie.length;
    }
    return unescape(document.cookie.substring(offset, endstr));
}
   
// primary function to retrieve cookie by name
function VistaGetCookie(name) {
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg) {
            return this.GetCookieVal(j);
        }
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break; 
    }
    return null;
}
   
// store cookie value with optional details as needed
function VistaSetCookie(name, value, expires, path, domain, secure) {
    var Cookie = name + "=" + escape (value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
    document.cookie = Cookie;
}

// remove the cookie by setting ancient expiration date
function VistaDeleteCookie(name,path,domain) {
    if (this.GetCookie(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

function VistaMapTypeFromString(MapType) {
    switch(MapType) {
        case 'G_NORMAL_MAP':
            return G_NORMAL_MAP;
        case 'G_SATELLITE_MAP':
            return G_SATELLITE_MAP;
        case 'G_HYBRID_MAP':
            return G_HYBRID_MAP;
        default:
            return null;
    }
}
        
function VistaMapTypeToString(MapType) {
    switch(MapType) {
        case G_NORMAL_MAP:
            return 'G_NORMAL_MAP';
        case G_SATELLITE_MAP:
            return 'G_SATELLITE_MAP';
        case G_HYBRID_MAP:
            return 'G_HYBRID_MAP';
        default:
            return '';
    }
}

// GridRowSelected: Flag a row as selected.

function VistaGridRowSelected(GridID, CellID) {
    var Grid = igtbl_getGridById(GridID);
    var Cell = igtbl_getCellById(CellID);
    var Rows = Grid.Rows;
    for (RowIndex = 0; RowIndex < Rows.length; ++RowIndex) {
        var Row = Rows.getRow(RowIndex);
        var SelectedCell = Row.getCellFromKey('Selected');
        SelectedCell.setValue(Row.Id == Cell.Row.Id);
    }
}

// Global Vista variable.

var VistaApp = new Vista();