var counter = 0;
if(typeof window.TRS == "undefined") {

	var TRS = {};

    TRS.ConfigMap = {
        ImagesBaseURL : "/trs/",
        ComponentsBaseURL : "http://174.129.2.203/trs/"
    };

	function RemoveQuotes(str)
	{
		return str.replace(/["'\t\r\n]/g, str);
	}

	function StateArray( wGroup )
	{
		var comboboxes = TRS.filterWidgetGroup($("select"), wGroup );
		var stateArray = {};
		for (var i=0; i<comboboxes.length;i++)
		{
			stateArray[comboboxes[i].name] = comboboxes[i].value;
		}
		var inputs = TRS.filterWidgetGroup($("input"), wGroup );
		for (var i=0; i<inputs.length;i++)
		{
			switch(inputs[i].type) {
				case "checkbox":
				case "radio":
					if (inputs[i].checked)
						stateArray[inputs[i].name] = inputs[i].value;
					break;
				case "text":
				case "hidden":
					stateArray[inputs[i].name] = inputs[i].value;
					break;
			}

		}
		return stateArray;
	}


	TRS.getDataCallback = function(response) {
      var data = response.responseData ;
      var widgetGroup = response.widgetGroup ;
      var additionalSerachParameters = "" ;
      // Revisit - Confirm that widgetGroup filtering cannot be done throug XPath
      var widgetized = widgetGroup != "" && widgetGroup != null && widgetGroup != undefined
	  for (var i = 0; i < data.length; i++) {
		TRS.filterWidgetGroup($("//[@name= " + data[i].dataProviderName + additionalSerachParameters + "]"), widgetGroup).each(function(){
			if( typeof $(this).attr('componentType') != 'undefined' && $(this).attr('componentType') != "" ) {
                if ( widgetized ){
				    TRS.TypeMap[$(this).attr('componentType')](data[i], widgetGroup );
                } else {
				    TRS.TypeMap[$(this).attr('componentType')](data[i]);
                }
			}
		});
	  }
	}

	TRS.ajaxError = function(xmlHttpRequest, errorStr, exception) {
	/* For dev related purposes enable this, for production this should be disabled
	*/
		/*alert("Cannot get data from the server. The current page may be inconsistent. "
		+ "Please refresh the page." + exception);*/
	}

	TRS.getData = function(dpName, additionalStates)
	{
        TRS.widgetgetData(dpName, additionalStates, "" ) ;
	}

	TRS.refresh = function(dpName, newValue)
	{
        TRS.widgetRefresh(dpName,newValue, "" ) ;
	}
    /**
      The method is the same as TRS.getData, except that it overrides
      sends the data only corresponding to that widget group.
    **/
	TRS.widgetgetData = function(dpName, additionalStates, wGroup)
    {
        var states = StateArray( wGroup );
		if (additionalStates != null) {
			for(var attr in additionalStates) {
				states[attr] = additionalStates[attr];
			}
		}
		var val = {name: dpName,
				  	value: "",
                    widgetGroup: wGroup,
				  	componentStates: states};
        TRS.showBusyBox() ;
        queryForData ( TRS.ConfigMap.ComponentsBaseURL + "trsdata" + "?value=" + encodeURIComponent(TRS.toJSON(val)), TRS.hideBusyBox ) ;
    }

    /**
      The method is the same as TRS.Refresh, except that it overrides
      sends the data only corresponding to that widget group.
    **/
	TRS.widgetRefresh = function(dpName, newValue, wGroup)
    {
        var val = {name: dpName,
				  	value: newValue,
                    widgetGroup: wGroup,
				  	componentStates: StateArray( wGroup )};
        TRS.showBusyBox() ;
        queryForData ( TRS.ConfigMap.ComponentsBaseURL + "trsrefresh" + "?value=" + encodeURIComponent(TRS.toJSON(val)), TRS.hideBusyBox ) ;
    }

    /**
      The method is responsible for filtering the elements, corresponding to the current widgetGroup
      queryResult should be the result returned by a jQuery selector call
     **/
    TRS.filterWidgetGroup = function( queryResult, widgetGroup )
    {
        if ( widgetGroup != null && widgetGroup != "" && widgetGroup != undefined ) {
            return queryResult.filter("[@widgetGroup=" + widgetGroup + "]");
        } else {
            return queryResult;
        }
    }


    TRS.escapeJSONChar =
	function escapeJSONChar(c)
	{
	    if(c == "\"" || c == "\\") return "\\" + c;
	    else if (c == "\b") return "\\b";
	    else if (c == "\f") return "\\f";
	    else if (c == "\n") return "\\n";
	    else if (c == "\r") return "\\r";
	    else if (c == "\t") return "\\t";
	    var hex = c.charCodeAt(0).toString(16);
	    if(hex.length == 1) return "\\u000" + hex;
	    else if(hex.length == 2) return "\\u00" + hex;
	    else if(hex.length == 3) return "\\u0" + hex;
	    else return "\\u" + hex;
	};


	TRS.escapeJSONString =
	function escapeJSONString(s)
	{
	    var parts = s.split("");
	    for(var i = 0; i < parts.length; i++) {
		var c = parts[i];
		if(c == '"' ||
		   c == '\\' ||
		   c.charCodeAt(0) < 32 ||
		   c.charCodeAt(0) >= 128)
		    parts[i] = escapeJSONChar(parts[i]);
	    }
	    return "\"" + parts.join("") + "\"";
	};

	TRS.toJSON = function toJSON(o)
	{
	    if(o == null) {
			return "null";
	    } else if(typeof o == "string") {
			return TRS.escapeJSONString(o);
	    } else if(typeof o == "number") {
			return o.toString();
	    } else if(typeof o == "boolean") {
			return o.toString();
	    } else if(typeof o == "object") {
		    if (o instanceof Array) {
				var v = [];
				for(var i = 0; i < o.length; i++) v.push(TRS.toJSON(o[i]));
				return "[" + v.join(", ") + "]";
		    } else {
				var v = [];
				for(attr in o) {
				    if(o[attr] == null) v.push("\"" + attr + "\": null");
				    else if(typeof o[attr] == "function"); /* skip functions */
				    else v.push(TRS.escapeJSONString(attr) + ": " + TRS.toJSON(o[attr]));
				}
				return "{" + v.join(", ") + "}";
	    	}
    	}
	};

	TRS.showBusyBox = function() {
    	//debugger;
        counter ++;
        if (counter > 1){
            return;
        }
        if($.browser.msie) {
			$("//select").attr("disabled","true")
		}
		$("body").css("height","99%");
		var height = document.documentElement.scrollHeight;
		var width = document.documentElement.scrollWidth;

		if ($.browser.safari) {

			if (height > 300) {
				  height = 5000;
				}
		}

    	$("#overlay").css({"height": height, "width": width});
    	$("#BusyBoxIFrame").css('visibility','visible');

       	if (typeof(busyBox ) != "undefined" && height > 84 && width > 260) {
       		try {
            	busyBox.Show();
    			busyBox.StartAnimate();
			} catch (err) {
				busyBox.Hide();
			}
		}
		setTimeout("TRS.hideBusyBox()", 20000);
	}

	TRS.hideBusyBox = function() {
        counter --;
        if (counter < 0) {
            counter = 0;
        }
        if (counter == 0) {
            if ($.browser.msie) {
                $("//select").removeAttr("disabled");
            }
            if (typeof(busyBox ) != "undefined")
                busyBox.Hide();

            $("#overlay").css({"height": "0", "width": "0"});
        }
	}

	TRS.initBusyBox = function() {
	$("body").append("<div id='overlay'></div>");

   	$("body").append("<iframe id='BusyBoxIFrame' style='display:block' ondrop='return false;' name='BusyBoxIFrame' frameBorder='0' scrolling='no'></iframe>");

    	busyBox = new BusyBox("BusyBoxIFrame", "busyBox", 8,
                TRS.ConfigMap.ComponentsBaseURL + "images/gears_ani_", ".gif", 125, "260pt", "84pt",
                TRS.ConfigMap.ComponentsBaseURL + "busybox.htm");


	}



	$(document).ready(function(){
		if (this.location.pathname.indexOf("properties.jsp") == -1)
		{

		//$("head").append("<link rel='stylesheet' type='text/css' href='css/busybox.css'>");
		//$("body").append("<script type='text/javascript' src='js/BusyBox.js'></script>");
		//$.getScript("http://localhost:8080/trs/js/BusyBox.js");
			TRS.initBusyBox();

    	}
 	});

 	TRS.submitadf = function() {
 		var modelID = $('#modelChoose option:selected').val();
 		var trim=$('#trimChoose option:selected').html();
	$.ajax(  {
			type: "POST",
			url: TRS.ConfigMap.ComponentsBaseURL + "adfsubmit",
			data: "modelID="+modelID+"&repositoryString="+repositoryStringGlobal+"&trim="+trim,
			success: function(msg){
    			alert( "Lead Submitted" );
  			},
			error: function(xmlHttpRequest, errorStr, exception) {
				TRS.ajaxError(xmlHttpRequest, errorStr, exception);
			}
		});
	};

}

/**
  By default there will be no type maps to add.
**/
TRS.TypeMap = {}

/**
  Queries the requested URL for the data. Done through the DynamicScript tag
  TODO: Callback is currently essential, fix it
**/
queryForData = function ( url, callback )
{
    var head = document.getElementsByTagName("head")[0];
    var script = document.createElement("script");
    script.src = url;
    var done = false ;
        // Attach handlers for all browsers
        script.onload = script.onreadystatechange = function(){
            if ( !done && (!this.readyState || 
                    this.readyState == "loaded" || this.readyState == "complete") ) {
                done = true;
                callback() ;
                head.removeChild( script );
            }
        };
    head.appendChild(script);
}
