// Top Navigation dropdowns for IE


var timeout	= 200;
var closetimer	= 0;
var ddmenuitem	= 0;

// open hidden layer
function mopen(id)
{
	// cancel close timer
	mcancelclosetime();

	// close old layer
	if(ddmenuitem) ddmenuitem.style.visibility = 'hidden';

	// get new layer and show it
	ddmenuitem = document.getElementById(id);
	ddmenuitem.style.visibility = 'visible';

}
// close showed layer
function mclose()
{
	if(ddmenuitem) ddmenuitem.style.visibility = 'hidden';
}

// go close timer
function mclosetime()
{
	closetimer = window.setTimeout(mclose, timeout);
}

// cancel close timer
function mcancelclosetime()
{
	if(closetimer)
	{
		window.clearTimeout(closetimer);
		closetimer = null;
	}
}

// close layer when click-out
document.onclick = mclose;









// Image Hover

		<!--
		function MM_swapImgRestore() { //v3.0
		  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
		}
		function MM_preloadImages() { //v3.0
		  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
			var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
			if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
		}

		function MM_findObj(n, d) { //v4.01
		  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
			d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
		  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
		  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
		  if(!x && d.getElementById) x=d.getElementById(n); return x;
		}

		function MM_swapImage() { //v3.0
		  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
		   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
		}
		//-->


// Map Function

		<!--
		function MyF(partN) {
		window.document.usa_locator.SetVariable("perem1", "state" + partN);
		}
		//-->

// Notice Handling
var invalidInput = false;
var myFieldArray = new Array();

function clearFormValidation()
{
    invalidInput = false;
    myFieldArray = Array();
    $("noticeContainer").innerHTML = "";
    $("noticeContainer").style.display = "none";
}

function validateInput(fieldName, fieldTitle)
{
    if($("navForm")[fieldName].value == "")
    {
        myFieldArray[myFieldArray.length] = fieldTitle;
        invalidInput = true;
        return false;
    }
    return true;
}

function getInvalidFieldHTML()
{
    var tmpHTML;
    tmpHTML = "<strong>The following fields are required:</strong><br/><ul>";
    for(i = 0; i < myFieldArray.length;i++)
    {
        tmpHTML += "<li>" + myFieldArray[i] + "</li>";
    }
    tmpHTML += "</ul>";
    return tmpHTML;
}

function notifyClient(notice)
{
    $("noticeContainer").innerHTML = notice;
    $("noticeContainer").style.display = "block";
}

Ext.onReady(function ()
{
    if (1 == window.check_browser_version && Ext.isIE6)
    {
        (new Ext.Window
        ({
           width: 450,
           bodyStyle: 'padding: 10px 0 0 0;',
           html:    '<div class="contentblock" style="border:2px #CC0000 solid;">'+
                    '<h2><a href="http://proof.centerdigitaled.com/Navigator/contract.html">Warning:</a><br />'+
                    '<div class="subhead"></div>'+
                    '</h2>'+
                        '<p>The Beta Navigator sites only support the following  browsers - </p>'+
                        '<p><strong>Internet Explorer 7.0+</strong> and <strong>Firefox 3.0+. </strong></p>'+
                        '<p>Logging in with any  other browser type will have unexpected results. </p>'+
                    '<p>Download the latest Internet Explorer or the latest Firefox:</p>'+
                    '<p>&nbsp;</p>'+
                    '<a href="http://www.microsoft.com/windows/Internet-explorer/default.aspx"><img src="/COMMON/themes/2009/common/images/downloadie.jpg" width="198" height="82" style="border-right:1px solid #999999; margin-right:3px;" alt="Download Internet Explorer"/></a><a href="http://www.mozilla.com/en-US/firefox/upgrade.html"><img  src="/COMMON/themes/2009/common/images/downloadfirefox.jpg"width="198" height="82" alt="Download Firefox"/></a>'+
                    '</div>',
           modal: true
        })).show();
    }
});

var hotlist_success_img = '/COMMON/themes/2009/common/images/ico_check_s.gif';
var hotlist_search_success_img = '/COMMON/themes/2009/common/images/ico_check.gif';
var hotlist_deal_success_img = '/COMMON/themes/2009/common/images/ico_subscribed_deal.png';


var hotlisted_items = get_hotlisted_items();
var buttons = Ext.query(".hotlist_button");
for(i=0;i < buttons.length;i++)
{
	if (hotlisted_items.indexOf(buttons[i].getAttribute("pk")) >= 0)
    {
    	if ((buttons[i].className).indexOf('hotlist_button_large') > -1)
		{
    		buttons[i].getElementsByTagName('img')[0].src = hotlist_deal_success_img;
		}
    	else
    	{
    		buttons[i].getElementsByTagName('img')[0].src = hotlist_success_img;
    	}
		buttons[i].style.cursor = 'default';
    }
}

var successHandler = function(response, opts)
{
    var result = Ext.util.JSON.decode(response.responseText);
    if (result.success != "true")
    {
        Ext.Msg.show({modal: false, title: 'Message', msg: "An error occurred while processing the request." });
    }
}

var failureHandler = function(response, opts)
{
    Ext.Msg.alert('Connectionhandler', 'Ajax request failed');
}

function get_file_name(path)
{
    var path_arr = path.split("/");
    return path_arr[path_arr.length -1];
}

function removeSelected(type)
{
    var hotlist_arr = Array();
    var checkboxes = Ext.query(".hotlistContainer-" + type + " .hotlistBoxes");
    for (var i=0; i < checkboxes.length; i++)
    {
        if (checkboxes[i].checked == false)
        {
            hotlist_arr[hotlist_arr.length] = checkboxes[i].value;
        }
        else
        {
            var childContainers =  Ext.query("#hotlistContainer-" + checkboxes[i].value);
            if (childContainers.length > 0)
            {
                var childContainer  = childContainers[0];
                var parentContainer = childContainer.parentNode;
            }
            if (parentContainer != undefined)
            {
                remove_hotlisted_item(checkboxes[i].value);
                parentContainer.removeChild(childContainer);
            }
        }
    }

     Ext.Ajax.request({
         url: '/COMMON/yaas.php',
         success: successHandler,
         failure: failureHandler,
         params: {
             data: Ext.util.JSON.encode(
                 [{
                     method: "YaasHotlist.SaveHotlist",
                     params: {type: type, items: hotlist_arr}
                 }]
             )
         }
     });
}

function selectAll(containerName)
{
    var checkboxes = Ext.query(containerName + " .hotlistBoxes");
    for (i=0; i < checkboxes.length; i++)
    {
        checkboxes[i].checked = 1;
    }
}

var AddItemHandler = function(response, opts)
{

    var data = Ext.util.JSON.decode(response.responseText);
    if (data.success == "true")
    {
        add_hotlisted_item(data.data[0].result)
    }
    successHandler(response, opts);
}

var confirmDealwatch = function(t)
{
	var confirmStr = 'Clicking Yes will subscribe you to this Deal. When updates come out for this Deal, you will be notified by e-mail. '
		 + 'This will also place this Deal in your Hotlist. To unsubscribe from the Deal, remove it from your Hotlist.'

	Ext.Msg.confirm('Subscribe to this Deal?', confirmStr, function(btn){
 	    if (btn == 'no'){
 	    	return;
 	    }
 	    else
 	    {
 	    	addToHotlist(t);
 	    }
 	});
}

var addToHotlist = function(t)
{
	Ext.Ajax.request({
        url: '/COMMON/yaas.php',
        success: AddItemHandler,
        failure: failureHandler,
        params: {
            data: Ext.util.JSON.encode(
                [{
                    method: "YaasHotlist.AddItem",
                    params: t.parentNode.getAttribute("pk")
                }]
            )
        }
    });

    if ((t.parentNode.className).indexOf('large') > -1)
    {
   	 	t.src = hotlist_deal_success_img;
    }
    else
    {
   	 	t.src = hotlist_success_img;
    }

    t.parentNode.style.cursor = 'default';
}

Ext.onReady(function() {
    Ext.addBehaviors({
        '.hotlist_button@click': function(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)
					&& get_file_name(t.src) != get_file_name(hotlist_deal_success_img))
            {
            	// is it a dealwatch item?
            	if ((t.parentNode.className).indexOf('dealwatch') > -1)
            	{
            		confirmDealwatch(t);
            	}
            	else
            	{
            		addToHotlist(t);
            	}
            }
        }
    });
});





function create_cookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var cookie_expires = "; expires="+date.toGMTString();
    }
    else
    {
        var cookie_expires = "";
    }
    document.cookie = name+"="+value+cookie_expires+"; path=/";
}

function read_cookie(name) {
    var cookie_key = name + "=";
    var cookie_arr = document.cookie.split(';');
    for(var i=0;i < cookie_arr.length;i++)
    {
        var c = cookie_arr[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(cookie_key) == 0)
        {
            return c.substring(cookie_key.length,c.length);
        }
    }
    return null;
}

function get_hotlisted_items()
{
	var items = unescape(read_cookie('hotlisted_items')).split(',');
    return items;
}

function add_hotlisted_item(num)
{
    hotlisted_items = get_hotlisted_items();
    hotlisted_items[hotlisted_items.length] = num;
    create_cookie('hotlisted_items', hotlisted_items.join(','), 365);
    return true;
}

function remove_hotlisted_item(num)
{
    hotlisted_items = get_hotlisted_items();
    var tmp_index = hotlisted_items.indexOf(parseInt(num));
    if (tmp_index != undefined)
    {
        hotlisted_items.splice(tmp_index, 1);
    }
    create_cookie('hotlisted_items', hotlisted_items.join(','), 365);
}

function isExternalAnchor(anchor)
{
	if (anchor.hostname != ''
		&& (anchor.href.indexOf('http://') != -1
		|| anchor.href.indexOf('https://') != -1)
		&& anchor.hostname != location.hostname
		&& anchor.host.split('.')[1] != location.host.split('.')[1]
		&& anchor.hostname != 'media.centerdigitalgov.com'
		&& anchor.hostname != 'media.govtech.net'
		&& anchor.hostname != 'www.erepublic.com'
		&& anchor.hostname != 'www.centerdigitalgov.com'
        && anchor.hostname != 'www.centerdigitaled.com'
	)
	{
		return true;
	}
	return false;
}

Ext.onReady(function() {
	var anchors = Ext.query("a");
	for(var i=0;i < anchors.length;i++)
	{
		if (isExternalAnchor(anchors[i]))
		{
			var anchor = Ext.get(anchors[i]);
			anchor.addClass('external');
			anchor.dom.target = '_blank';
		}
	}
});

function setStateFilter(val)
{
	$('#stateFilter option').each(function() {
		if ($(this).val() == val)
		{
			$(this).attr("selected", "true");
			return false;
		}
		else
		{
			$(this).attr("selected", "false");
		}
	});
}

function filterByState(elem)
{
	var url = window.location.href.split('?')[0];
	var newUrlPart = "state=" + elem.value;
	if (url && url.length > 0)
	{
		if(url.indexOf('state') != -1)
		{
			var pos = url.indexOf('state=');
			var firstPart = url.substr(0, pos);
			newUrlPart = firstPart + newUrlPart;
		}
	}

	newUrl = window.location.href.split('?')[0];
	newUrl = newUrl.split('#')[0];
	window.location = newUrl + "?" + newUrlPart;
}

function markHotlist()
{
    var hotlisted_items = get_hotlisted_items();
    var buttons = Ext.query(".hotlist_button");

    for(i=0;i < buttons.length;i++)
    {
        if (hotlisted_items.indexOf(buttons[i].getAttribute("pk")) >= 0)
        {
            if ((buttons[i].className).indexOf('hotlist_button_large') > -1)
            {
                buttons[i].getElementsByTagName('img')[0].src = hotlist_deal_success_img;
            }
            else
            {
                buttons[i].getElementsByTagName('img')[0].src = hotlist_success_img;
            }
            buttons[i].style.cursor = 'default';
        }
    }

    Ext.addBehaviors({
        '.hotlist_button@click': function(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)
					&& get_file_name(t.src) != get_file_name(hotlist_deal_success_img))
            {
            	// is it a dealwatch item?
            	if ((t.parentNode.className).indexOf('dealwatch') > -1)
            	{
            		confirmDealwatch(t);
            	}
            	else
            	{
            		addToHotlist(t);
            	}
            }
        }
    });
}
