﻿/*  This is the method that will decode/decompress/de-obfuscate 
    the Json string returned from the web service.
*/
function DecodeJsonResponse(Response) { return Response; }

/*  This function provides some additional handling for template tokens.
    If a value doesn't exist as part of an object, - is returned instead of undefined.
    If a value has html tags, innerHTML is used to display the item.
    Otherwise a text node is created and added.
*/
function processTokenValue(parentElement, value)
{
    if (!value) { parentElement.appendChild(document.createTextNode("n/a")); }
    else if (typeof(value) == "string") 
    {
        if (value.indexOf("<") > -1 && value.indexOf(">") > -1) { parentElement.innerHTML += value; }
        else { parentElement.appendChild(document.createTextNode(value)); }
    }
    else { parentElement.appendChild(value); }
}

/*  This function is fired after a AJAX Request is successfully responded.
    It decodes then deserializes the response json string.
    The data is attached to the appropriate datasource and the render method is called.
    Finally the filters attached to this datasource are filtered.
*/
function ReceiveServerResponse(response, userContext, methodName)
{
    //Get the datasource from the parameters.
    var dataSource = userContext;
    
    debugWindow.add(new jsTraceEvent(dataSource.name + " data received", "ReceiveServerResponse()"));
    dataSource.data = response;
    
    // Filter the filters based on the data.
    debugWindow.add(new jsTraceEvent("Begin " + dataSource.name + ".filterFilters()", "ReceiveServerResponse()"));
    dataSource.filterFilters();
    debugWindow.add(new jsTraceEvent("End " + dataSource.name + ".filterFilters()", "ReceiveServerResponse()"));    
    
    // Call the render method of the datasource
    dataSource.render();
}

   /*  This function is fired after a AJAX Request has failed.
   It writes the context and error information into the Trace block
   which is only displayed when standard trace information is shown
   via debugme=true or similar mechanism.
   */
function FailedCallback(error, userContext)
{
	//Get the datasource from the parameters.
	var dataSource = userContext;

	debugWindow.add(new jsTraceEvent("Error in Callback"), "FailedCallback(error, userContext)");
	debugWindow.add(new jsTraceEvent("UserContext:" + Sys.Serialization.JavaScriptSerializer.serialize(userContext), "FailedCallback(error, userContext)"));
	var stackTrace = error.get_stackTrace();
	var message = error.get_message();
	var statusCode = error.get_statusCode();
	var exceptionType = error.get_exceptionType();
	var timedout = error.get_timedOut();

	debugWindow.add(new jsTraceEvent(exceptionType + " Error:" + statusCode + " - " + message, "FailedCallback(error, userContext)"));
	debugWindow.add(new jsTraceEvent("StackTrace:" + stackTrace, "FailedCallback(error, userContext)"));
	debugWindow.add(new jsTraceEvent("Timedout:" + timedout, "FailedCallback(error, userContext)"));
}


/*  This creates the javascript for a datasource's refresh function
    The refresh consist of calling the datasource URI and then
    calling ReveiveServerResponse Javascript function once the
    server response has been received. 
*/ 
function dataSource_refresh() 
{
    debugWindow.add(new jsTraceEvent(this.name + ".refresh() called", dsRegistryName));
    this.webService.set_defaultSucceededCallback(ReceiveServerResponse);
    this.webService.set_defaultFailedCallback(FailedCallback);
    this.webService.set_defaultUserContext(this);
    this.webService[this.webMethod](parameters);
    debugWindow.add(new jsTraceEvent(this.name + " data requested",dsRegistryName));

}

/*  This creates a datasource's render method. This method calls the render method
    of each of the datasource's registered controls.
*/
function dataSource_render() 
{
    for (ctlIndex in this.registeredControls) 
    {
        debugWindow.add(new jsTraceEvent(ctlIndex + ".render() called", dsRegistryName + ".render()"));
        this.registeredControls[ctlIndex].datasource = this;
        this.registeredControls[ctlIndex].render();
        debugWindow.add(new jsTraceEvent(ctlIndex + " rendered", dsRegistryName + ".render()"));
    }
}

/*  This creates a datasource's filter_click method. When a filter item is selected, it calls this 
    method and sends the filter Group the filter is a memeber of.
*/
function dataSource_filter_click(filterGroup) 
{
    debugWindow.add(new jsTraceEvent("Begin filter for " + this.name, this.name + ".filter_click('" + filterGroup + "')"));
    updateChecked(filterGroup, this);
    this.render();
    debugWindow.add(new jsTraceEvent("End filter for " + this.name, this.name + ".filter_click('" + filterGroup + "')"));
}

/*  This creates a datasource's applyFilter method. This method is called by the render method to determine if 
    a particular jsObj (Json Phone Object) meets the filter criteria. It returns boolean.
*/
function dataSource_applyFilter(jsObj) 
{
    var retval = true;
    for (groupKey in this.filterGroups)
    {
        if (!this.filterGroups[groupKey].checkedItems) { updateChecked(groupKey, this); }
        if (this.filterGroups[groupKey].checkedItems.length > 0) 
        {
            if (typeof(this.filterGroups[groupKey].applyFilter) == "string")
            {
                eval("this.filterGroups[groupKey].applyFilter = " + this.filterGroups[groupKey].applyFilter);
            }
            
            retval &= this.filterGroups[groupKey].applyFilter(jsObj);
            
            if (!retval) { break; }
        }
    }
    return retval;
}

/*  This javascript function clears all checked filter items and clears out the cached list of checked items. */
function dataSource_resetFilters() 
{
    for (groupKey in this.filterGroups)
    {
        for (itemKey in this.filterGroups[groupKey].checkedItems)
        {
            if ($get(this.filterGroups[groupKey].checkedItems[itemKey].htmlObject))
            {
                $get(this.filterGroups[groupKey].checkedItems[itemKey].htmlObject).checked = false;
                $get(this.filterGroups[groupKey].checkedItems[itemKey].htmlObject).parentNode.parentNode.style.backgroundImage= '';
            }
        }
        this.filterGroups[groupKey].checkedItems = new Array();
    }
    this.render(); 
    return false;
}

/*  This function tests existing filters against the data. If a filter cannot be associated with any 
    phone object, it is hidden and removed from the list of filters.
*/
function dataSource_filterFilters() 
{
    for (groupKey in this.filterGroups) 
    {
        for (filterKey in this.filterGroups[groupKey].filterItems) 
        {
            var validFilter = false;
            var filterItem = this.filterGroups[groupKey].filterItems[filterKey];
            if (!filterItem.Settings.value) { $get(filterItem.htmlObject).parentNode.parentNode.style.display = "block"; continue; }
            for (dataIndex in this.data)
            {
                jsObj = this.data[dataIndex];
                validFilter = (eval(filterItem.jsObj) == filterItem.Settings.value);
                if (validFilter) { break; }
            }
            if (!validFilter){ $get(filterItem.htmlObject).parentNode.parentNode.parentNode.removeChild($get(filterItem.htmlObject).parentNode.parentNode); }
            else { $get(filterItem.htmlObject).parentNode.parentNode.style.display = "block"; } 
        }
    }
}

/*  This is the initialize function for the json DataSourceRegistry object.
    It converts its variables from string values into json objects/javascript methods.
    It also fires off the refresh method, which instructs each datasource to go get its data.
*/
function dsRegistry_init(dsRegistry)
{
    for (regKey in dsRegistry) 
    {
        eval("dsRegistry[regKey].webService = " + dsRegistry[regKey].webService);
        eval("dsRegistry[regKey].refresh = " + dsRegistry[regKey].refresh);
        eval("dsRegistry[regKey].render = " + dsRegistry[regKey].render);
        eval("dsRegistry[regKey].filterFilters = " + dsRegistry[regKey].filterFilters);
        eval("dsRegistry[regKey].filter_click = " + dsRegistry[regKey].filter_click);
        eval("dsRegistry[regKey].applyFilter = " + dsRegistry[regKey].applyFilter);
        eval("dsRegistry[regKey].resetFilters = " + dsRegistry[regKey].resetFilters);
        
        for (ctlKey in dsRegistry[regKey].registeredControls)
        {
            eval("dsRegistry[regKey].registeredControls[ctlKey] = " + dsRegistry[regKey].registeredControls[ctlKey]);
        }
        
        dsRegistry[regKey].refresh();
    }
}

var PhonesPanelHasData = true;

function BaseJsonControl_defaultRender() 
{ 
    
    if ($get(this.loader)) 
    {
        clearTimeout(this.clearLoader);
        $get(this.loader).style.position = "absolute";
        $get(this.loader).style.backgroundPosition = "center 45px"
        $get(this.loader).style.display = "block";
        if (isIE) 
        {
        	$get(this.loader).style.left = $get(this.loader).parentNode.offsetLeft + $get("wrapper").offsetLeft + "px";

        	if ($get(this.loader).id.indexOf("FeaturedPhones") == -1) {
        		var target = $get(this.target);
        		var top = 0;
        		while (target.tagName != "BODY") {
        			top += target.offsetTop;
        			target = target.offsetParent;
        		}
        		$get(this.loader).style.top = top + 19 + "px";
        	}
     }
     
     else {

         if ($get(this.loader).id.indexOf("FeaturedPhones") == -1) {
             $get(this.loader).style.top = $get(this.loader).parentNode.offsetTop + 50 + "px";
         }
     }
     
        $get(this.loader).style.height = $get(this.loader).parentNode.offsetHeight - 19 + "px";
    }
    
    while($get(this.target).hasChildNodes()) { $get(this.target).removeChild($get(this.target).firstChild); }    
    if (this.datasource.data && this.datasource.data.length >= this.minimum)
     {   
           
             /*Start code added for 30210 by VL*/  
             /*Displaying radio buttons Thunmnails/Lists when there is data for the phones panel*/ 
             
              $get("Content_headerViewControlBox").style.display = "block";
              
             /*End code added for 30210 by VL*/       
        var domObj;
        for (var dataIdx = 0; dataIdx < this.datasource.data.length && (this.maximum == -1 || dataIdx < this.maximum); dataIdx++) 
        {               
            if (!this.usesFilter || this.datasource.applyFilter(this.datasource.data[dataIdx])) 
            {
                domObj = this.template(this.datasource.data[dataIdx]);
                $get(this.target).appendChild(domObj);
            }
        }
     
        if (!($get(this.target).hasChildNodes()))
        {
            domObj = this.noresultstemplate("");
            if (domObj) {$get(this.target).appendChild(domObj);}
        }
        
        if (this.usesCurvyCorners)
        {
            if (domObj && domObj.className) 
            {
                (new curvyCorners({tl: { radius: 10 },tr: { radius: 10 },bl: { radius: 10 },br: { radius: 10 },antiAlias: true,autoPad: false,validTags: ["div"]},domObj.className)).applyCornersToAll();
            }
        }
    } 
    var loader = this.loader;
    if ($get(this.loader)) { this.clearLoader = setTimeout(function() { $get(loader).style.display = "none"; }, 750); }    
    if (!($get(this.target).hasChildNodes()) && $get(this.loader)) { $get(this.loader).parentNode.style.display = "none"; }
    
    /*Start code added for 30210 by VL*/
   /* Displaying Error message when there is no data for the phones panel and hiding the Thumnail/List radio buttons */
     if (!($get(this.target).hasChildNodes()))
        {
            
            domObj = this.nodatatemplate("");          
            if (domObj) 
            {
            $get(this.target).appendChild(domObj);
            
            $get("Content_headerViewControlBox").style.display = "none"; 
            
            $get(loader).style.display = "block";
            $get(this.loader).parentNode.style.display = "block";           
            PhonesPanelHasData = false;//addition for PRN   31178 
            toggleView("ViewThumbnails");
            }
          
       }
         /*End code added for 30210 by VL*/
}

