function CreateQueryString(values, path)
{
    var query = path + '?';
        
    for (var i in values)
    {
        query += i + "=" + values[i] + "&";
    }

	return query.slice(0, -1);
}

function GetjurinstData()
{
	var host = location.hostname.split('.');
	var site = host[1];
	var data = {};
	
	if (site == 'navigatored')
	{
        data.jurinst = "Institutions";
        data.search_btn_path = '/COMMON/themes/2009/ed/images/den_search_btn.jpg';
        data.reset_btn_path = '/COMMON/themes/2009/ed/images/den_reset_btn.jpg';
	}
	else if (site == 'navigatorgov')
	{
		data.jurinst = "Jurisdictions";
		data.search_btn_path = '/COMMON/themes/2009/gov/images/dgn_search_btn.jpg';
		data.reset_btn_path = '/COMMON/themes/2009/gov/images/dgn_reset_btn.jpg';
	}
	else if (site == 'navigatorem')
	{
		data.jurinst = "Jurisdictions";
		data.search_btn_path = '/COMMON/images/emn/emn_search_btn.jpg';
		data.reset_btn_path = '/COMMON/images/emn/emn_reset_btn.jpg';
	}
	
	return data;
}

function GetQueryString()
{
	var query_string;
	
	if (location.pathname.indexOf('/search') > -1 && location.search != '')
    {
    	query_string = {};
    	
    	var raw_query = location.search.substr(1).split("&");
        
        for (var i = 0; i < raw_query.length; i++)
        {
            var tmp = raw_query[i].split("=");
            query_string[tmp[0]] = tmp[1];
        }
    }
    
    return query_string;
}

function isChecked(obj, key, value)
{
	var found = false;

	if (obj && obj[key] && (location.pathname.indexOf("/search") > -1))
	{
        var tmp = obj[key].split(",");
	   
	    for (var i = 0; i < tmp.length; i++)
	    {
            if (value == unescape(tmp[i]))
            {
                found = true;
            }
	    }
	}
	
	return found;
}

// EXT BUTTON HANDLERS

function checkForAll(fieldset, specialcase)
{
	var allcheckbox;
    var allchecked = true;
    
	if (specialcase)
	{
		var fieldsets = fieldset.items;
		allcheckbox = fieldsets.first();
		
		fieldsets.each(function(item, index, length)
		{
			if (index) // skip 0 index -- it is the all checkbox
			{
				if (item.items)
				{
    				item.items.each(function(i, ix, l)
    				{
    					if (!i.checked)
    					{
    						allchecked = false;
    					}
    				}, this);
				}
			}
		}, this);
	}
	else
	{
		var checkboxes = fieldset.items;
		allcheckbox = checkboxes.first();
		
        for (var i = 1; i < checkboxes.getCount() - 1; i++)
        {
        	if (!checkboxes.get(i).checked)
        	{
        		allchecked = false;
        	}
        }
	}
	
	if (allchecked && allcheckbox)
    {
		allcheckbox.suspendEvents();
        allcheckbox.setValue(allchecked);
        allcheckbox.resumeEvents();
    }
}

function allCheckboxHandler(b, checked)
{
    b.ownerCt.items.each(function(item, index, length)
    {
    	if (item.xtype == 'checkbox')
    	{
    		item.suspendEvents();
            item.setValue(checked);
            item.resumeEvents();
    	}
    }, this);
}
    
function singleAllCheckboxHandler(b, checked)
{
    if (!checked)
    {
        var allCheckbox = b.ownerCt.items.first();
        allCheckbox.removeListener("check", allCheckboxHandler);
        allCheckbox.setValue(checked); // set false
        allCheckbox.addListener("check", allCheckboxHandler);
    }
}

// COMMON FIELDS
function GetKeywordField()
{
    var qString = GetQueryString();
    
    var keywords = qString && qString.keywords ? unescape(qString.keywords) : null;
    
    return new Er.TextField({name:'keywords', fieldLabel:'Keywords', hideLabel:true, value: keywords, emptyText:'Keywords', enableKeyEvents: true});
}

function GetStatesField()
{
    var qString = GetQueryString();
    var stateItems = [];
    var stateCode, stateName;
    var checked = (!qString || isChecked(qString, "allStates", "1"));
    
    
    stateItems.push(new Er.CheckBoxField({name: 'allStates', inputValue: 1, boxLabel: 'All', checked: checked, listeners:{check: allCheckboxHandler}}));
    
    for (var i = 0; i < Er.StatesArray.length; i++)
    {
        stateCode = Er.StatesArray[i][0];
        stateName = Er.StatesArray[i][1];
        
        stateItems.push(new Er.CheckBoxField(
        {
            name: 'states', 
            inputValue:stateCode, 
            boxLabel:stateName,
            checked: (!qString || isChecked(qString, "states", stateCode)), 
            listeners: 
            {
                check: singleAllCheckboxHandler
            }
        }));
    }

    return stateItems; 
}

function GetAgencyTypesField(types)
{
    var qString = GetQueryString();
    var agencyTypeItems = [];
    
    agencyTypeItems.push(
        new Er.CheckBoxField(
        {
            name: 'allAgencies', 
            inputValue: 1, 
            boxLabel: 'All',
            checked: (!qString || isChecked(qString, "allAgencies", "1")), 
            listeners:{check: allCheckboxHandler}
        })
    );
    
    for (var i = 0; i < types.length; i++)
    {
        agencyTypeItems.push(
            new Er.CheckBoxField(
            {
                name: 'agency_types', 
                checked: (!qString || isChecked(qString, "agency_types", types[i].pk)), 
                inputValue: types[i].pk, 
                boxLabel: types[i].title,
                listeners:{check: singleAllCheckboxHandler}
            })
        );
    }
    
    return types.length ? agencyTypeItems : [];
}

function GetResetBtn(handler)
{
    var jurinst = GetjurinstData();
  
    return {html: "<a href='javascript:void(0);' onclick='"+handler+"(); return false;' style='margin:3px 0 3px 0!important; display:block; height:22px!important; width:50px!important;'><img border=0 src='"+jurinst.reset_btn_path+"' /></a>"}		
}

function GetSearchBtn(handler)
{
    var jurinst = GetjurinstData();
    
    return {xtype: 'label', html: "<a href='javascript:void(0);' onclick='"+handler+"(); return false;' style='margin:3px 0 3px 0!important; height:22px!important; display:block; width:50px!important;'><img border=0 src='"+jurinst.search_btn_path+"' /></a>"}
}

function GetjurinstField()
{
    var qString = GetQueryString();
    var jurinst = GetjurinstData().jurinst;
    
    var checked = isChecked(qString, "jurinst", jurinst);
    
    var label = 'By ' + (jurinst == 'Jurisdictions' ? 'Location/' : '') + jurinst;
    
    return new Er.CheckBoxField({name:'jurinst', checked: checked, boxLabel: label, inputValue: jurinst});    
}


function GetEdLevelsField()
{
    var qString = GetQueryString(), levelItems = [];

    levelItems.push(new Er.CheckBoxField({name: 'allLevels', inputValue: 1, boxLabel: 'All', checked: (!qString || isChecked(qString, "allLevels", "1")), listeners:{check: allCheckboxHandler}}));
    
    levelItems.push(new Er.CheckBoxField({name: 'levels', checked: (!qString || isChecked(qString, "levels", "DOE")), inputValue: 'DOE', boxLabel: 'State DOE',listeners:{check: singleAllCheckboxHandler}}));
    levelItems.push(new Er.CheckBoxField({name: 'levels', checked: (!qString || isChecked(qString, "levels", "K12")), inputValue: 'K12', boxLabel: 'K12 District',listeners:{check: singleAllCheckboxHandler}}));
    levelItems.push(new Er.CheckBoxField({name: 'levels', checked: (!qString || isChecked(qString, "levels", "PUBLIC_UNIVERSITY")), inputValue: 'PUBLIC_UNIVERSITY,PRIVATE_UNIVERSITY,COMMUNITY_COLLEGE', boxLabel: 'Higher Education',listeners:{check: singleAllCheckboxHandler}}));
    levelItems.push(new Er.CheckBoxField({name: 'levels', checked: (!qString || isChecked(qString, "levels", "REGIONAL")), inputValue: 'REGIONAL', boxLabel: 'Regional',listeners:{check: singleAllCheckboxHandler}}));
    
    return levelItems;
}

function GetGovLevelsField()
{
    var qString = GetQueryString(), levelItems = [];
    
    levelItems.push(new Er.CheckBoxField({name: 'allLevels', inputValue: 1, boxLabel: 'All', checked: (!qString || isChecked(qString, "allLevels", "1")), listeners:{check: allCheckboxHandler}}));
    levelItems.push(new Er.CheckBoxField({name: 'levels', checked: (!qString || isChecked(qString, "levels", "STATE")), inputValue: 'STATE', boxLabel: 'State',listeners:{check: singleAllCheckboxHandler}}));
    levelItems.push(new Er.CheckBoxField({name: 'levels', checked: (!qString || isChecked(qString, "levels", "CITY")), inputValue: 'CITY,CONSOLIDATED', boxLabel: 'City',listeners:{check: singleAllCheckboxHandler}}));
    levelItems.push(new Er.CheckBoxField({name: 'levels', checked: (!qString || isChecked(qString, "levels", "COUNTY")), inputValue: 'COUNTY,CONSOLIDATED', boxLabel: 'County',listeners:{check: singleAllCheckboxHandler}}));
    
    var regional_values = [];
    regional_values.push("REGIONAL");
    
    if (location.host.indexOf('navigatorem') !== -1)
    {
    	regional_values.push("UASI");
    	regional_values.push("FUSION_CENTER");
    }
    
    levelItems.push(new Er.CheckBoxField({name: 'levels', checked: (!qString || isChecked(qString, "levels", "REGIONAL")), inputValue: regional_values.join(","), boxLabel: 'Regional',listeners:{check: singleAllCheckboxHandler}}));
    
    return levelItems;
}

function GetDateRangeField()
{
    var qString = GetQueryString();
    var sdate = qString && qString.date_range ? unescape(qString.date_range) : 365;
    var start_date = new Er.ComboBoxField(
    {
        hiddenName: 'date_range', 
        fieldLabel: 'Published Date Range',
        labelStyle:'font-size:7pt;', 
        style:'padding:0 !important; margin:0 !important;',
        store: 
        [
           [30, 'Last 30 Days'],
           [60, 'Last 60 Days'], 
           [90, 'Last 3 Months'], 
           [365, 'Last 12 Months'],
           [730, 'Last 24 Months']
        ]
    });
    
    start_date.setValue(sdate);
    
    return start_date;
}

function GetStartDateField()
{
    var qString = GetQueryString();
    
    var today = new Date();
    var yesterday = new Date(today.setDate(today.getDate() - 365));
    
    var sdate = qString && qString.start_date? unescape(qString.start_date) : yesterday;
    var start_date = new Er.DateField({name:'start_date', fieldLabel:'Start Date', value: sdate});
    
    return start_date;
}

function GetEndDateField()
{
    var qString = GetQueryString();
    
    var edate = qString && qString.end_date? unescape(qString.end_date) : new Date();
    var end_date = new Er.DateField({name:'end_date', fieldLabel:'End Date', value: edate});
    
    return end_date;
}

function GetPublishField()
{
    var qString = GetQueryString();
    var Items = [];
    
    Items.push(new Er.RadioButtonField(
    {
        name: 'status',
        inputValue: 'published',
        checked: (!qString || !qString.status || isChecked(qString, "status", "published")),
        boxLabel: 'Published'
    }));
    
    Items.push(new Er.RadioButtonField(
    {
        name: 'status',
        inputValue: 'unpublished',
        checked: isChecked(qString, "status", "unpublished"),
        boxLabel: 'Unpublished'
    }));
    
    return Items;
}

function ArrayToCheckboxFieldset(title, array, cbName, boxLabel, valueField)
{
    var options, items = [];

    var allName = 'all'+cbName.charAt(0).toUpperCase() + cbName.substr(1);
    var checked = isSelected(allName, 1);

    items.push(new Er.CheckBoxField({name: allName, inputValue: 1, boxLabel: 'All', checked: checked, listeners:{check: allCheckboxHandler}}))
    
    for (var i = 0; i < array.length; i++)
    {
        options = {};

        if (boxLabel != null || valueField != null)
        {
            options.boxLabel = array[i][boxLabel];
            options.value = array[i][valueField];
            options.inputValue = array[i][valueField];
        }
        else
        {
            options.boxLabel = array[i];
            options.value = array[i];
            options.inputValue = array[i];
        }
        
        options.name = cbName;

        options.checked = isSelected(cbName, options.value);
        options.listeners = {check: singleAllCheckboxHandler};

        items.push(new Er.CheckBoxField(options));
    }

    options = {};
    options.items = items;
    options.title = title;
    options.collapsed = true;
    options.collapsible = true;
    options.titleCollapse = true;
    
    var fieldset = new Er.FieldSet(options);

    return fieldset;
}

function isSelected(label, value)
{
    var selected = false;
    
    if (location.search)
    {
        var raw_query = location.search.substr(1);
        var query_array = raw_query.split('&');
        var query_values = {};
        var query_set;

        for (var i = 0; i < query_array.length; i++)
        {
            if (query_array[i].trim() != '')
            {
	            query_set = query_array[i].split("=");
	            
	            query_values[query_set[0]] = query_set[1].split(",");
            }
        }
      
        if (query_values[label])
        {
	        for (var i = 0; i < query_values[label].length; i++)
	        {
	            if (value == unescape(query_values[label][i]))
	            {
	                selected = true;
	                break;
	            }
	        }
        }
    }
    else
    {
        // Defaults to true;
        selected = true;
    }
    
    return selected;
}

function check_hotlist_button()
{
    var buttons = Ext.query(".hotlist_button_custom");
    for(i=0;i < buttons.length;i++)
    {
        buttons[i].childNodes[0].src = hotlist_search_success_img;
    }
    var tmp_nodes = Ext.query("#search_hotlist_status");
    if (tmp_nodes != undefined)
    {
        tmp_nodes[0].innerHTML = 'Search is Hotlisted';
    }
    Ext.addBehaviors({
        '.hotlist_button_custom@mouseover': function(e, t) {
            t.style.cursor = 'default';
        }
    });
}

function hotlist_search_dialogue(e, t) {
    if (get_file_name(t.src) != get_file_name(hotlist_success_img) && get_file_name(t.src) != get_file_name(hotlist_search_success_img))
    {
        Ext.Msg.prompt('Search Name', 'Enter a name for search:', function(btn, text) {
            if (btn == 'ok')
            {
                 Ext.Ajax.request({
                     url: '/COMMON/yaas.php',
                     success: successHandler,
                     failure: failureHandler,
                     params: { 
                         data: Ext.util.JSON.encode(
                             [{
                                 method: "YaasHotlist.AddSearch",
                                 params: {name: text, uri: location.href} 
                             }]
                         ) 
                     }
                 });
                 check_hotlist_button();
             }
         });
     }
}

function onLoadCheckSearchHotlist()
{
    Ext.Ajax.request({
        url: '/COMMON/yaas.php',
        success: function(response, opts)
        {
            var result = Ext.util.JSON.decode(response.responseText);
            if (result.success == "true" && result.data.length > 0)
            {
                check_hotlist_button();
            }
        },
        failure: failureHandler,
        params: {
            data: Ext.util.JSON.encode(
                [{
                    method: "YaasHotlist.IsSavedSearch",
                    params: location.href
                }]
            )
        }
    });
    Ext.addBehaviors({
        '.hotlist_button_custom@click': hotlist_search_dialogue
    });
}
