// JScript File
var divBasicFilters, divAdvancedFilters;
var radFilterType;
var hidFilters, hidFilterType, hidCurrentPage;
var chkCompare, chkAdvFilters, chkBasicFilters;
var qs = new Array();

function init()
{
    startList();
    
    // checkbox code
    radFilterType = document.getElementsByName("radFilterType");
    hidFilters = document.getElementById("hidFilters");
    hidFilterType = document.getElementById("hidFilterType");
    hidCurrentPage = document.getElementById("hidCurrentPage");
    chkCompare = document.getElementsByName("chkCompare");
    chkAdvFilters = document.getElementsByName("chkAdvFilters");
    //chkBasicFilters = document.getElementsByName("chkBasicFilters");

	chkAdvFilters = new Array();
    chkBasicFilters = new Array();   
    
    var ctrlInputs = document.getElementsByTagName("input");
    for (i = 0; i < ctrlInputs.length; i++)
    {
        if (ctrlInputs[i].name.indexOf("chkBasicFilters") > -1)
        {
            chkBasicFilters.push(ctrlInputs[i]);
        }
        if (ctrlInputs[i].name.indexOf("chkAdvFilters") > -1)
        {
            chkAdvFilters.push(ctrlInputs[i]);
        }
    }




    
    for (i = 0; i < chkCompare.length; i++)
    {
        chkCompare[i].onclick = function() { CheckMaxCompare(this);}
    }
    
    // accordian stuff
    // Sidebar Accordion controls
	var tier1 = document.getElementsByClassName('sb_t1');
	var tier2 = document.getElementsByClassName('sb_t1box');

	// Create the accordian	
	var foldTier1 = new fx.Accordion(tier1, tier2, {opacity: false, onComplete: function(){
			forceRedraw(document.getElementById('shell'));
		}
	});


	// Filtering Behaviors and List Collapse
	$S('#active_filters').action({
		initialize: function(){
			this.style.display = 'none';
		}   
	});
	
	$S('h5 span').action ({
		onclick: function(){
			var checkOpen = 0;
			if(this.className == 'open'){
				checkOpen = 1;
			}
			$S('h5 span.open').action({
				initialize: function(){
					if(this.className == 'open'){
						this.className = 'closed';
					}
				}
			});
			if(checkOpen == 1){
				this.className = 'closed';
			} else { this.className = 'open'; }
		}
	});
	
	$S('.sb_t4','.sb_t5').action({
		initialize: function(){
			toggleDiv = new fx.Combo(this, {duration:250, height:true, width:false, opacity:false, onComplete:function(){
				if ($(this).offsetHeight > 0) $(this).style.height = "auto";
			}});
			toggleDiv.hide();
		}
	});
	
	$S('span.sb_t4_hdr').action ({
		onclick: function(){	
			if(this.parentNode.className == "closed"){
				this.parentNode.className = "open";
			} else {
				this.parentNode.className = "closed";
			}
			if(this.nextSibling.nextSibling.className == 'sb_t4'){
				tierFour = this.nextSibling.nextSibling;
				$S(tierFour).action({
					initialize: function(){
						toggleDiv = new fx.Combo(this, {duration:250, height:true, width:false, opacity:false, onComplete:function(){
							if ($(tierFour).offsetHeight > 0) $(tierFour).style.height = "auto";
						}});
						toggleDiv.toggle();
						forceRedraw(document.getElementById('shell'));
					}
				});
			}
		}
	});
	
	$S('.sb_t5_hdr').action ({
		onclick: function(){	
			if(this.parentNode.className == "closed"){
				this.parentNode.className = "open";
			} else {
				this.parentNode.className = "closed";
			}
			if(this.nextSibling.nextSibling && this.nextSibling.nextSibling.className == 'sb_t5'){
				tierFive = this.nextSibling.nextSibling;
				$S(tierFive).action({
					initialize: function(){
						toggleDiv = new fx.Combo(this, {duration:250, height:true, width:false, opacity:false});
						toggleDiv.toggle();
						forceRedraw(document.getElementById('shell'));
					}
				});
			}
			else if(this.nextSibling && this.nextSibling.className == 'sb_t5'){
				tierFive = this.nextSibling;
				$S(tierFive).action({
					initialize: function(){
						toggleDiv = new fx.Combo(this, {duration:250, height:true, width:false, opacity:false});
						toggleDiv.toggle();
						forceRedraw(document.getElementById('shell'));
					}
				});
			}
		}
	});
	
	$S('li.filter_item').action({
		onclick: function(){
			if(this.className != 'inactive_filter'){
				var spanHTML = this.getElementsByTagName("span")[0].innerHTML;
				var inputValue = this.getElementsByTagName("input")[0].value;

				if (inputValue == "" || inputValue == null)
				{
					inputValue = this.firstChild.nextSibling.value;
				}
				addFilter(spanHTML, inputValue);
			}
		}			
	});
	
	$S('input.basic_checkbox').action({
		onclick: function(){
		    var spanHTML = this.nextSibling.innerHTML;
		    addFilter(spanHTML, this.value);
			/*if(this.className != 'inactive_filter'){
				var spanHTML = this.getElementsByTagName("span")[0].innerHTML;
				var inputValue = this.getElementsByTagName("input")[0].value;

				if (inputValue == "" || inputValue == null)
				{
					inputValue = this.firstChild.nextSibling.value;
				}
				addFilter(spanHTML, inputValue);
			}*/
		}			
	});
	
	// check for qs parameters being passed in to the page
	GetQueryString();
	var filterType = "basic";
    var page = GetParameter("page");
	
	// comments start here by Deepak
	/* 
	if (typeof(qs["filtertype"]) != "undefined")
    {
        if (qs["filtertype"].toLowerCase() != "basic")
        {
            radFilterType[1].checked = true;
            filterType = "advanced";
        }
    }
	*/ // comments ends here by Deepak

    // Code added by Deepak
	if (filterTypeStr.toLowerCase() != "basic")
	{
		 radFilterType[1].checked = true;
         filterType = "advanced";
	}
	// Code ends here by Deepak
    
	//if (typeof(qs["filter"]) != "undefined") // by Metia , Commented by Deepak
	//if (true) // Added by Deepak , this condition is not required ;)
	if (filterSavingStr != "notSet")
	{
        //var selectedArray = qs["filter"].split(","); // by Metia , Commented by Deepak


		//var someStr = "manufacturer.name=;Nokia;,deviceType INCLUDES ITEM (name=;Internet-enabled Phones; )";
		//alert(someStr);		
		var selectedArray = filterSavingStr.split(","); // Added by Deepak


        if (selectedArray.length > 0)
        {
            if (filterType != "basic")
            {
                CheckCheckboxes(selectedArray, chkAdvFilters);
                divBasicFilters = document.getElementById("divBasicFilters");
                divAdvancedFilters = document.getElementById("divAdvancedFilters");
                divBasicFilters.style.display = "none";
                divAdvancedFilters.style.display = "block";
            }
            else
            {
                CheckCheckboxes(selectedArray, chkBasicFilters);
                divBasicFilters = document.getElementById("divBasicFilters");
                divAdvancedFilters = document.getElementById("divAdvancedFilters");
                divBasicFilters.style.display = "block";
                divAdvancedFilters.style.display = "none";
            }
        }
    }
    
    addFilter();
        
    if (typeof(qs["page"]) != "undefined")
    {
        hidCurrentPage.value = qs["page"];
    }
    
    //(tetheringSupportBluetooth=;Integrated; or tetheringSupportBluetooth=;Accessory;)
}

function BasicCheckBoxClick(obj)
{
    var checkBox = document.getElementsByName(obj.name);
    CheckForNoSelection(checkBox);
    UnCheckShowAll(checkBox);
}

function ShowBasicFilter()
{
    divBasicFilters = document.getElementById("divBasicFilters");
    divAdvancedFilters = document.getElementById("divAdvancedFilters");
    divBasicFilters.style.display = "block";
    divAdvancedFilters.style.display = "none";
    
    var selectedArray = GetCheckBoxValues(chkAdvFilters).split(",");
    ClearAllCheckBoxes(chkBasicFilters);
    CheckCheckboxes(selectedArray, chkBasicFilters);
    addFilter();
}

function ShowAdvancedFilter()
{
    divBasicFilters = document.getElementById("divBasicFilters");
    divAdvancedFilters = document.getElementById("divAdvancedFilters");
    divBasicFilters.style.display = "none";
    divAdvancedFilters.style.display = "block";
    
    var selectedArray = GetCheckBoxValues(chkBasicFilters).split(",");
    ClearAllCheckBoxes(chkAdvFilters);
    CheckCheckboxes(selectedArray, chkAdvFilters);
    addFilter();
}

function CheckCheckboxes(selectedArray, checkBox)
{
    for (i = 0; i < selectedArray.length; i++)
    {
        var selectedValue = unescape(selectedArray[i]);
        if (selectedValue != "")
        {
            for (j = 0; j < checkBox.length; j++)
            {
                if (selectedValue == checkBox[j].value)
                {
                    checkBox[j].checked = true;
                    break;
                }
            }
        }
    }
}

function CheckForNoSelection(checkBox)
{
     // check for no selections
    var checkCount = 0;
    for (i = 0; i < checkBox.length; i++)
    {
        if (checkBox[i].checked) 
        { 
            checkCount++; 
            break;
        }
    }
    
    if (checkCount == 0) 
    { 
        checkBox[0].checked = true; 
    }
}

function UnCheckShowAll(checkBox)
{
    var checkCount = 0;
    for (i = 1; i < checkBox.length; i++)
    {
        if (checkBox[i].checked) 
        { 
            checkCount++; 
            break;
        }
    }
    
    if (checkCount > 0) 
    { 
        checkBox[0].checked = false; 
    }
}

function ApplyFilter(page)
{
    var filterType = "basic";
    if (!radFilterType[0].checked) { filterType = "advanced"; }
    
    hidFilters.value = "";
    if (typeof(page) == "undefined") { page = 1; }
    
    if (filterType == "basic")
    {
        hidFilterType.value = "basic";        
        hidFilters.value = GetCheckBoxValues(chkBasicFilters);
    }
    else
    {
        hidFilterType.value = "advanced";
        hidFilters.value = GetCheckBoxValues(chkAdvFilters);
    }
    
    // comment this out when in production
    var msg = "Populating the querystring with the following filters:\n" + hidFilters.value + "\n\n";
    msg += "Display Page:\n" + page + "\n\n";
    msg += "Search Type:\n" + filterType;
    //alert(msg);
    
	// Commented by Deepak Starts here
    //document.location.href="devices_browse.html?filter=" + hidFilters.value + "&page=" + page + "&filtertype=" + filterType;
	
	document.device_list_form.XXX.value=hidFilters.value;
	document.device_list_form.userFilter.value=hidFilters.value;
	document.device_list_form.userFilterType.value=filterType;
	document.device_list_form.submit();
	// Commented by Deepak Ends here
}

function CheckMaxCompare(checkBox)
{
    if (GetCheckBoxCheckedCount(chkCompare) >= 4)
    {
        checkBox.checked = false;
        alert("You may select only 3 devices to compare");
    }
}

function GetCheckBoxValuesForCompare(checkBox)  // Code modified by Deepak
{
    var checkBoxValues = "";
    for (i = 0; i < checkBox.length; i++)
    {
        if (checkBox[i].checked) 
        { 
            checkBoxValues += checkBox[i].value + "&id="; 
        }
    }
    
    if (checkBoxValues != "")
    {
        checkBoxValues = checkBoxValues.substring(0, checkBoxValues.length-1);
    }
        
    return checkBoxValues;
}

function GetCheckBoxValues(checkBox)
{
    var checkBoxValues = "";
    for (i = 0; i < checkBox.length; i++)
    {
        if (checkBox[i].checked) 
        { 
            checkBoxValues += checkBox[i].value + ","; 
        }
    }
    
    if (checkBoxValues != "")
    {
        checkBoxValues = checkBoxValues.substring(0, checkBoxValues.length-1);
    }
        
    return checkBoxValues;
}


function GetCheckBoxLabels(checkBox)
{
    var checkBoxLabels = "";
    for (i = 0; i < checkBox.length; i++)
    {
        if (checkBox[i].checked) 
        { 
            if (checkBox[i].nextSibling.nodeValue != null)
            {
                checkBoxLabels += checkBox[i].nextSibling.nodeValue + ","; 
            }
            else
            {
                checkBoxLabels += checkBox[i].nextSibling.innerHTML + ","; 
            }
        }
        
    }
    
    if (checkBoxLabels != "")
    {
        checkBoxLabels = checkBoxLabels.substring(0, checkBoxLabels.length-1);
    }
        
    return checkBoxLabels;
}

function GetCheckBoxCheckedCount(checkBox)
{
    var checkedCount = 0;
    for (i = 0; i < checkBox.length; i++)
    {
        if (checkBox[i].checked)
            checkedCount++;
    }
    
    return checkedCount;
}

function Compare()
{
    //var compareValues = GetCheckBoxValues(chkCompare); // commented by Deepak
	var compareValues = GetCheckBoxValuesForCompare(chkCompare);
    //if (compareValues == "" || compareValues.split(",").length == 0) // commented by Deepak
	if (compareValues == "" || compareValues.split("&").length == 0)
    {
        alert("You must select at least 2 devices to compare");
    }
    else
    {
        document.location.href="device_compare.jsp?id=" + compareValues;
		//document.location.href="device_compare.html?id=" + compareValues;
    }
}


function addFilter(filterName, filterParameter)
{	
	try
	{
		$S('#active_filters').action({
		initialize: function(){
			if(this.style.display == 'none'){
				this.style.display = 'block';
				}
			}
		});	
	}
	catch (e)
	{
		var active_filters_div = document.getElementById("active_filters");
		if (active_filters_div.style.display == 'none')
		{
			active_filters_div.style.display = 'block';
		}
	}
	
	var filters_div = document.getElementById("filters");
	filters_div.innerHTML = "";
	
	var selectedFiltersArray = "";
	if (radFilterType[0].checked)
	{
	    selectedFiltersArray = GetCheckBoxLabels(chkBasicFilters).split(",");
	}
	else
	{
	    selectedFiltersArray = GetCheckBoxLabels(chkAdvFilters).split(",");
	}
	
    for (i = 0; i < selectedFiltersArray.length; i++)
    {
        if (selectedFiltersArray[i] != "")
            filters_div.innerHTML += "<p>" + selectedFiltersArray[i] + " <a href='javascript:RemoveFilter(" + i + ")'>(remove)</a></p>";
    }
	
	if (filters_div.innerHTML == "")
    {
        var active_filters_div = document.getElementById("active_filters");
        active_filters_div.style.display = "none";
    }
}

function ClearAll()
{
    var chk = null;
    if (radFilterType[0].checked)
	{
	    chk = chkBasicFilters;
	}
	else
	{
	    chk = chkAdvFilters;
	}
	
    ClearAllCheckBoxes(chk);
    var active_filters_div = document.getElementById("active_filters");
    active_filters_div.style.display = "none";
}

function ClearAllCheckBoxes(checkBox)
{
    for (i = 0; i < checkBox.length; i++)
    {
        checkBox[i].checked = false;
    }
}

function RemoveFilter(idx)
{
    var count = 0;
    var chk = null;
    
    if (radFilterType[0].checked)
	{
	    chk = chkBasicFilters;
	}
	else
	{
	    chk = chkAdvFilters;
	}

    
    for (i = 0; i < chk.length; i++)
    {
        if (chk[i].checked)
        {
            if (count == idx)
            {
                chk[i].checked = false;
                break;
            }
            count++;
        }
    }
    
    addFilter();
}

function setCookie(name, value, expire) {   
    document.cookie = name + "=" + escape(value)  + ((expire == null) ? "" : ("; expires=" + expire.toGMTString()))
}

function getCookie(Name) {   
    var search = Name + "="   
    if (document.cookie.length > 0) { 
        // if there are any cookies      
        offset = document.cookie.indexOf(search)       
        if (offset != -1) { 
            // if cookie exists          
            offset += search.length          
            // set index of beginning of value         
            end = document.cookie.indexOf(";", offset)          
            // set index of end of cookie value         
            if (end == -1)             
                end = document.cookie.length
                
            return unescape(document.cookie.substring(offset, end))      
        }    
    }
}

function GetQueryString() 
{
	var query = window.location.search.substring(1);
	var parms = query.split('&');
	
	for (var i=0; i<parms.length; i++) 
	{
		var pos = parms[i].indexOf('=');
	
		if (pos > 0) 
		{
			var key = parms[i].substring(0,pos);
			var val = parms[i].substring(pos+1);
			qs[key] = val;
		}
	}
}

function GetParameter(key)
{
    var ret = "";
    try
    {
        if (typeof(qs[key]) != "undefined")
        {
            ret = qs["key"];
        }
    }
    catch(e)
    {
        ret = "";
    }
    
    return ret;
}