var toContactLimit = 10;
var toContact = [];
var toContactFranchise = [];
var curSearch = [];
var randAr = randomizeArray(arFranFeat)
var curPage = 1;
var pageSize = 36;
var iTotalInv = 0;
var div1Index = [0,4,8,12,16,20,24,28,32];
var div2Index = [1,5,9,13,17,21,25,29,33];
var div3Index = [2,6,10,14,18,22,26,30,34];
var div4Index = [3,7,11,15,19,23,27,31,35];

function add_to_contact(id){
    var present = false;
    for(key in toContact){
        if(toContact[key] == id) present = true;
    }
    if(!present){
        toContact.push(id);
        toContactFranchise.push(arFranAll[id][0]);
    }
    setToContactStatus();
}

function changeSearch(f){
    var ar = randAr;
    var ddlCat = document.getElementById('ddlCategory');
    var ddlSubCat = document.getElementById('ddlSubCategory');
    var ddlST = document.getElementById('ddlLocation');
    var ddlIL = document.getElementById('ddlInvestmentLevel');
    
    if(ddlCat.selectedIndex > 0){
        ar = ar.unsortedIntersect(arFranFeatCat[ddlCat.options[ddlCat.selectedIndex].value]);
    }
    if(ddlSubCat.selectedIndex > 0){
        ar = ar.unsortedIntersect(arFranFeatSubcat[ddlSubCat.options[ddlSubCat.selectedIndex].value]);
    }
    if(ddlST.selectedIndex > 0){
        ar = ar.unsortedIntersect(arFranFeatStateAll.unsortedUnion(arFranFeatState[ddlST.options[ddlST.selectedIndex].value]));
    }
    if(ddlIL.selectedIndex > 0){
        ar = ar.unsortedIntersect(arFranFeatIL[ddlIL.options[ddlIL.selectedIndex].value]);
    }
    curSearch = ar;
    curPage = 1;
    updateList();
}

function remove_from_contact(id){
    var present = false;
    for(key in toContact){
        if(toContact[key] == id){
            present = key;
        }
    }
    if(present){
        toContact.splice(present,1);
        toContactFranchise.splice(present,1);
    }
    setToContactStatus();
}

function setToContactStatus(){
    var rs = toContact.length + " of " + toContactLimit;
    $('toContactStatus').update(rs);
}

function setToContactBackground(){
}
function getFranchise(id,type){
    var rs = "";
    var short_name = arFranAll[id][1].length < 19 ? arFranAll[id][1] : arFranAll[id][1].substr(0,18) + "&hellip;"
    rs += "<div class=\"franchise\" id=\"" + type + id + "\" style=\"display:none;\">";
    if(type == 'A') rs += "<a href=\"/selector/info.asp?franchise_id=" + arFranAll[id][0] + "\" class=\"lightwindow page-options\" params=\"lightwindow_type=external,lightwindow_width=600,lightwindow_loading_animation=false\" title=\"" + arFranAll[id][1] + " Information\">";
    rs += "<img src=\"http://www.findafranchise.com/_img/_franchise/" + arFranAll[id][0] + "/" + arFranAll[id][2] + "\" height=\"60\" width=\"120\" border=\"0\"  id=\"s" + type + "IMG" + id + "\">";
    if(type == 'A') rs += "</a>"
    rs += "<div class=\"info\" id=\"s" + type + "I" + id + "\">"
    rs += "<div class=\"namelink\">"
    if(type == 'A') rs += "<a href=\"/selector/info.asp?franchise_id=" + arFranAll[id][0] + "\" class=\"lightwindow page-options\" params=\"lightwindow_type=external,lightwindow_width=600,lightwindow_loading_animation=false\" title=\"" + arFranAll[id][1] + " Information\">";
    rs += short_name
    if(type == 'A') rs += "</a>"
    rs += "</div>";
    if(type == 'F'){
        rs += "<div class=\"detail_but\"><div class=\"d1\"><div>Min. Liquid Capital:<br>" + arFranAll[id][5] + "</div></div><div class=\"d2\"><div>Required Investment:<br>" + arFranAll[id][3] + "</div></div><div class=\"d3\"><div>Total Investment:<br>" + arFranAll[id][3] + " - " + arFranAll[id][4] + "</div></div><div class=\"d4\"><div>Financial Assistance:<br>" + arFranAll[id][6] + "</div></div></div>"
        rs += "</div>"
    } else {
        rs += "</div>";
    }
    if(type == 'F'){
        rs += "<div class=\"links\"><a href=\"/selector/info.asp?franchise_id=" + arFranAll[id][0] + "&id=" + id + "\" onClick=\"openWindow('/selector/info.asp?franchise_id=" + arFranAll[id][0] + "&id=" + id + "',650,800,true); return false;\" title=\"" + arFranAll[id][1] + " Information\">more info</a> | <span class=\"addlink\" id=\"s" + type + "L" + id + "\">add &gt;&gt;</span></div>";
    } else if(type == 'C'){
        rs += "<div class=\"links\"><span class=\"addlink\" id=\"s" + type + "L" + id + "\"><< remove</span> | <a href=\"/selector/info.asp?franchise_id=" + arFranAll[id][0] + "\" onClick=\"openWindow('/selector/info.asp?franchise_id=" + arFranAll[id][0] + "&id=" + id + "',650,800,true); return false;\" title=\"" + arFranAll[id][1] + " Information\">more info</a></div>";
    } else {
        rs += "<div class=\"links\"><a href=\"/selector/info.asp?franchise_id=" + arFranAll[id][0] + "&id=" + id + "\" onClick=\"openWindow('/selector/info.asp?franchise_id=" + arFranAll[id][0] + "&id=" + id + "',650,800,true); return false;\" title=\"" + arFranAll[id][1] + " Information\">more info</a></div>";
    }
    rs += "</div>";
    return rs;
}

function getAFranchise(id,type,action){
    var rs = "";
    var short_name = arFranAll[id][1].length < 17 ? arFranAll[id][1] : arFranAll[id][1].substr(0,16) + "&hellip;"
    
    if(type == 'F')
    {
        rs = "<div class=\"listing\" id=\"" + type + id + "\" style=\"display:none;\">";
        rs += "<img src=\"http://www.findafranchise.com/_img/_franchise/" + arFranAll[id][0] + "/" + arFranAll[id][2] + "\" height=\"58\" width=\"118\" title=\"Click for Info on " + arFranAll[id][1] + "\" style=\"border:1px solid #243e90;margin:1px 1px 1px 1px;cursor:pointer;\" id=\"s" + type + "IMG" + id + "\">";
        rs += "<div class=\"group\" id=\"s" + type + "I" + id + "\">"
        rs += "<div class=\"namelink\">"
        rs += short_name
        rs += "</div></div>"
        rs += "<div class=\"accordianHeader\" id=\"s" + type + "INF" + id + "\"><div class=\"fInfo\" style=\"cursor:pointer;\">Financial Info"
        rs += "<img id=\"s" + type + "IMGINF" + id + "\" src=\"images/arrowDown.gif\" height=\"10\" width=\"7\" class=\"morefininfo\" style=\"cursor:pointer;\" id=\"fi" + type + "IMG" + id + "\">";
        rs += "</div></div>"
        rs += "<div><div class=\"minliquid\" id=\"dInfo1\"><div><img src=\"images/greenBullet.gif\">&nbsp;Liquid Capital: " + arFranAll[id][5] + "</div></div><div id=\"dInfo" + id + "\" style=\"display:none;\" ><div class=\"liquid\" ><div><img src=\"images/greenBullet.gif\">&nbsp;Required Investment:<br>&nbsp;&nbsp;&nbsp;" + arFranAll[id][7] + "</div></div><div class=\"liquid\" ><div><img src=\"images/greenBullet.gif\">&nbsp;Total Investment:<br>&nbsp;&nbsp;&nbsp;" + arFranAll[id][3] + (arFranAll[id][3] == "" || arFranAll[id][4] == ""? "" : " - ") + arFranAll[id][4] + "</div></div><div class=\"liquid\" ><div><img src=\"images/greenBullet.gif\">&nbsp;Financial Assistance:<br>&nbsp;&nbsp;&nbsp;" + arFranAll[id][6] + "</div></div></div></div>"
        rs += "<div id=\"div" + id + "\" class=\"moreAdd\"><a href=\"#\" id=\"a" + id + "\" class=\"bottomLinks\" title=\"" + arFranAll[id][1] + " Information\">More Info</a><span class=\"pipe\">&nbsp;&nbsp;|</span>&nbsp;<a href=\"#\" class=\"bottomLinks\" id=\"s" + type + "L" + id + "\">Add &gt;&gt;</a></div>";
    }
    else if (type == 'C')
    {
        rs = "<div id=\"" + type + id + "\" style=\"display:" + (action == true ?"block" : "none")+ ";\">";
        rs += "<img src=\"http://www.findafranchise.com/_img/_franchise/" + arFranAll[id][0] + "/" + arFranAll[id][2] + "\" height=\"56\" width=\"118\" title=\"Click for Info on " + arFranAll[id][1] + "\" style=\"border:1px solid #243e90;margin:1px 1px 0px 1px;cursor:pointer;\" id=\"s" + type + "IMG" + id + "\">";
        rs+=  "<div style=\"float:left;\"><a href=\"#\" class=\"removecolor\" id=\"s" + type + "I" + id + "\">" + short_name + "</a>"
        rs += "<div style=\"float:left;\"><a class=\"removecolor\" href=\"#\" id=\"s" + type + "L" + id + "\"><< Remove</a><div style=\"color:#243e90;display:inline;\">&nbsp;&nbsp;|&nbsp;</div><a class=\"removecolor\" href=\"#\" id=\"a" + type + "L" + id + "\" title=\"" + arFranAll[id][1] + " Information\">More Info</a></div></div>";
    }
    
    rs += "</div>";
    return rs;
}
function getBlankSelection(id,type)
{
    return "<div id=\"D" + type + id + "\" class=\"selections\"><span>Selection#" + id + "</span></div>";
}
function displayInfoPopup(e,type)
{
        var a = $(Event.element(e)).ancestors();
        a.each(function(item){
            if(item.identify().charAt(0) == type /* "F" */){
                var id = item.identify().substr(1);
                displayPopup(id,type);
            }
        })
}
function displayPopup(id,type)
{
    $("gHead").show();
    $("divSave").hide();

    $("divContent").style.height= "409px";
    $("lblCompanyName").innerHTML = arFranAll[id][1];
    $("lblPopupMinimumCapital").innerHTML = arFranAll[id][5];
    $("lblPopupRequiredInvestment").innerHTML = arFranAll[id][7];
    $("lblPopupTotalInvestment").innerHTML = arFranAll[id][3] + (arFranAll[id][3] == "" || arFranAll[id][4] == ""? "" : " - ") + arFranAll[id][4];
    $("lblPopupFinancialAssistance").innerHTML = arFranAll[id][6];
    $("hdnAddPopupFranchiseId").value = type + id;
    
    if (type == "C" )
        $("btnAddPopupContact").style.display = 'none';
    else
        $("btnAddPopupContact").style.display = 'block';
    
    $("divContent").innerHTML = getMoreInfoProgressBar();
    if ($find('ModalPopupExtender') != null)
        $find('ModalPopupExtender').show(); 
    
    //Call ajax to get content data, pass franchiseid
    getContent(arFranAll[id][0],0);
}
function display_financial_info(e)
{
        var a = $(Event.element(e)).ancestors();
        a.each(function(item){
            if(item.identify().charAt(0) == "F"){
                var id = item.identify().substr(1);
                if ($('dInfo' + id).style.display == 'none')
                {
                    $('div' + id).className = 'moreAddOpen';
                    $('F' + id).className = 'nolisting';
                    $('sFIMGINF' + id).src = 'images/arrowUp.gif';              
                    $('sFIMGINF' + id).title = 'Click to close more financial info'
                    $('sFIMGINF' + id).alt = 'Click to close more financial info'
                    $('dInfo' + id).style.display = 'block'; 
                }
                else
                {
                    $('div' + id).className = 'moreAdd';
                    $('F' + id).className = 'listing';
                    $('sFIMGINF' + id).src = 'images/arrowDown.gif';              
                    $('sFIMGINF' + id).title = 'Click for more financial info'
                    $('sFIMGINF' + id).alt = 'Click for more financial info'
                    $('dInfo' + id).style.display = 'none';               
                }
            }
        })
}
function right_panel_paging(id)
{
    if ($(id).src.indexOf("pageDown.gif") >= 0)
    {
        if (toContact.length > 5)
        {       
            $(id).src = "images/pageUp.gif";
            $('divPage1').hide();
            $('divPage2').show();
        }
    }
    else
    {
        $(id).src = "images/pageDown.gif";
        $('divPage2').hide();
        $('divPage1').show();
    }
}
function redisplay_on_remove(idx)
{
    $('divPage1').hide();
    $('divPage2').hide();
    idx = idx - 1;
    if (idx <= 3)
    {
        $('divPage1').show() 
    }
    else
    {
        if (toContact.length > 5)   
            $('divPage2').show();
        else
            $('divPage1').show();
    }
    
    $('divPage1').innerHTML = "";
    $('divPage2').innerHTML = "";

    for (i = 1; i <= 10 ; i ++)
    {
        if (i <= 5)
            $('divPage1').insert({bottom: getBlankSelection(i,'C')});
        else
            $('divPage2').insert({bottom: getBlankSelection(i,'C')});
    };     

    for (i = 0 ; i < toContact.length; i ++)
    {
        $('DC' + (i +1).toString()).innerHTML = "";
        $('DC' + (i +1).toString()).insert({bottom: getAFranchise(toContact[i],'C',true)});
        
        Effect.BlindDown('C'+toContact[i], {beforeStart: setToContactBackground});
        Event.observe('sCI'+toContact[i], 'click', function(event){displayInfoPopup(event,"C")});
        Event.observe('sCIMG'+toContact[i], 'click', function(event){displayInfoPopup(event,"C")});
        Event.observe('sCL'+toContact[i], 'click', function(event){return !confirm('Are you sure you want to remove this franchise from your contact list?') || remove_from_contact_click(event)});
        Event.observe('aCL'+toContact[i], 'click', function(event){displayInfoPopup(event,"C")});
    };     
    calculate_min_capital();
}
function calculate_min_capital()
{
    var min_max = 0;
    var min_max_str = "";
    var min_cap = 0;
    
    for(var i = 0; i < toContact.length ; i++)
    { 
         min_cap = arFranAll[toContact[i]][5].replace("<nobr>$","").replace("</nobr>","").replace(",","");
         if (min_cap != "" && parseInt(min_cap) > parseInt(min_max))
         {
            min_max = min_cap;   
            min_max_str = arFranAll[toContact[i]][5].replace("<nobr>","").replace("</nobr>","");
         }
    }
    $("lblMinimumLiquidCaptial").innerHTML = (min_max_str == ""? "$0" : min_max_str);
}
function getMoreInfoProgressBar()
{
    var rs = "";
    rs =  "<div id=\"imgDiv\" class=\"moreinfoProgress\">";
    rs += "<span style=\"vertical-align:middle;\">";
    rs += "<img alt=\"\" style=\"vertical-align:middle;\" src=\"images/loading.gif\" border=\"0\" />";
    rs += "<b>&nbsp;Loading data, please wait for a moment...<b/></span>";
    rs += "</div>";
    return rs;

}
function add_to_contact_click(e){
    scrollPos = $("divGrids").scrollTop;
    
    if(toContact.length >= toContactLimit){
        alert("Sorry! You have reached the maximum number franchises in your contact list.");
    } else {
        var a = $(Event.element(e)).ancestors();
        a.each(function(item){
            if(item.identify().charAt(0) == "F"){
                var id = item.identify().substr(1);
                add_to_contact(id);
                Effect.Fade('F'+id);
                if (toContact.length > 5)
                {
                    $('divPage1').hide();
                    $('divPage2').show();
                    $('imgDownArrow').src = "images/pageUp.gif";
                }
                else
                {
                    $('divPage2').hide();
                    $('divPage1').show();
                    $('imgDownArrow').src = "images/pageDown.gif";
                }
                $('DC' + toContact.length.toString()).innerHTML = "";
                $('DC' + toContact.length.toString()).insert({bottom: getAFranchise(id,'C',false)});
                
                Effect.BlindDown('C'+id, {beforeStart: setToContactBackground});
                Event.observe('sCI'+id, 'click', function(event){displayInfoPopup(event,"C")});
                Event.observe('sCIMG'+id, 'click', function(event){displayInfoPopup(event,"C")});
                Event.observe('sCL'+id, 'click', function(event){return !confirm('Are you sure you want to remove this franchise from your contact list?') || remove_from_contact_click(event)});
                Event.observe('aCL'+id, 'click', function(event){displayInfoPopup(event,"C")});
                calculate_min_capital();
                updateList(false);
                new Effect.ScrollTo("divGrids",{duration:0,offset:scrollPos});
            }
        })
    }
}
function add_to_contact_from_info(id){
    myLightWindow.deactivate();
    if(toContact.length >= toContactLimit){
        alert("Sorry! You have reached the maximum number franchises in your contact list.");
    } else {
        $('loading').show();
        add_to_contact(id);
        Effect.Fade('F'+id);
        $('listToContact').insert({top: getFranchise(id,'C')});
        Effect.BlindDown('C'+id, {beforeStart: setToContactBackground});
        Event.observe('sCI'+id, 'click', function(event){return !confirm('Are you sure you want to remove this franchise from your contact list?') || remove_from_contact_click(event)});
        Event.observe('sCIMG'+id, 'click', function(event){return !confirm('Are you sure you want to remove this franchise from your contact list?') || remove_from_contact_click(event)});
        Event.observe('sCL'+id, 'click', function(event){return !confirm('Are you sure you want to remove this franchise from your contact list?') || remove_from_contact_click(event)});
        updateList(false);
        refreshLightwindowLinks();
        $('loading').hide();
    }
}

function remove_from_contact_click(e){
    var a = $(Event.element(e)).ancestors();
    a.each(function(item){
        if(item.identify().charAt(0) == "C"){
            var id = item.identify().substr(1);
            var idx = toContact.indexOf(id); 
            //Effect.BlindUp('C'+id, {afterFinish: setToContactBackground});
            remove_from_contact(id);
            redisplay_on_remove(idx);
            updateList(false);
        }
    })
}

function remove_all_after_contact(){
    addContacted = [];
    toContact.each(function(item){
        contactedFranchise.push(arFranAll[item][0]);
        addContacted.push(arFranAll[item][0]);
    });
    toContact = [];
    toContactFranchise = [];
    redisplay_on_remove(1);    
    //updateContacted(addContacted);
    setToContactStatus();
}

function start_load(cat,st,il){
    setToContactStatus();
    setToContactBackground();
    $('state_id').selectedIndex = st ? st-1 : 0;
    $('invest_level_id').selectedIndex = il ? 34-il : 0;
    var idx = 0;
    $$('option.category_opts').each(function(opt) {if (opt.value == cat) {idx = opt.index}});
    $('category_id').selectedIndex = idx ? idx : 0;
    changeSearch();
    updateContacted(contactedFranchise);
    refreshLightwindowLinks();
}

function updateContacted(franIn){
    if(franIn.length > 0 && franIn[0] != ""){
        $('contacted').update("You have contacted the following franchises with the franchise selector:");
        franIn.each(function(item){
            if(item != ""){
                var id = "";
                arFranAll.each(function(f,index){if(f[0] == item){id = index; throw $break;}});
                if(id != ""){
                    $('contactedDetail').insert(getFranchise(id,'A'));
                    Effect.Appear('A'+id);
                }
            }
        });
    $('contacted').show();
    $('contactedDetail').show();
    refreshLightwindowLinks();
    }
}

function insertFranchise(i,divId){
    if($('F'+i) == null){
        $(divId).insert(getAFranchise(i,'F',false));
        Event.observe('sFI'+i, 'click', function(event){displayInfoPopup(event,"F")});
        Event.observe('sFIMG'+i, 'click', function(event){displayInfoPopup(event,"F")});
        Event.observe('sFL'+i, 'click', function(event){add_to_contact_click(event);});
        Event.observe('sFINF'+i, 'click', function(event){display_financial_info(event)});
        Event.observe('a'+i, 'click', function(event){displayInfoPopup(event,"F")});
    }
}

function updateList(ap){
    $('no_results').hide();
    
    $('divColumn1').innerHTML = "";
    $('divColumn2').innerHTML = "";
    $('divColumn3').innerHTML = "";
    $('divColumn4').innerHTML = "";

    var pg = curPage;
    var ar = curSearch;
    var len = curSearch.length;
    var first =((pg-1)*pageSize);
    var last = ((pg)*pageSize);
    var tc = 0;
    last = last < len ? last : len;
    for(var i = 0; i < len; i++){
        var inToContact = false;
        toContact.each(function(item){if(item == curSearch[i]) inToContact = true;})
        contactedFranchise.each(function(item){if(item == arFranAll[curSearch[i]][0]) inToContact = true;})
        if(inToContact){
            tc++;
        }
    }
    var k = 0;
    for(var i = first; k < pageSize && i < ar.length; ){
        var inToContact = false;
        toContact.each(function(item){if(item == curSearch[i]) inToContact = true;})
        contactedFranchise.each(function(item){if(item == arFranAll[curSearch[i]][0]) inToContact = true;})
        if(!inToContact){
        
            if (div1Index.indexOf(k) >=0)
                insertFranchise(ar[i],'divColumn1');
                
            if (div2Index.indexOf(k) >=0)
                insertFranchise(ar[i],'divColumn2');
            
            if (div3Index.indexOf(k) >=0)
                insertFranchise(ar[i],'divColumn3');
            
            if (div4Index.indexOf(k) >=0)
                insertFranchise(ar[i],'divColumn4');

            Effect.Appear('F'+ar[i]);
            k++;    
        }
        i++;
    }
    if(k == 0){
        $('no_results').show();
    }
    resetPaging(pg,first, first+pageSize > len? len : first+pageSize,len);
}

function updatePage(pg){
    curPage = pg;
    updateList(true);
}

function resetPaging(pg,first,last,len){
    var rs = rs2 = "";
    var next = false;
    if(len > pageSize){
        for(var i = 1; i <= Math.ceil(len/pageSize); i++){
            if(i == pg){
                rs += "<a class=\"selected\">&nbsp;" + i + "&nbsp;</a>";
                next = pg + 1;
            } else {
                rs += "&nbsp;<a href='javascript:updatePage(" + i + ")'>" + i + "</a>&nbsp;"
            }
        }
        if(pg != 1 && i != 1) rs = "&nbsp;<a href='javascript:updatePage(" + (pg - 1) + ")'><< Back</a>&nbsp;" + rs;
        if(next > pg && pg != i-1) rs += "&nbsp;<a href='javascript:updatePage(" + next + ")'>Next >></a>&nbsp;"
    }
    if (last == 0 && len == 0)
        rs2 = "";
    else
        rs2 += (first+1) + " to " + last + " of " + len
        
    $('pages').update(rs);
    $('status').update(rs2);
}

function randomizeArray(ar){
    var ar2 = [];
    while(ar2.length < ar.length){
        var rand_num = Math.floor(Math.random() * ar.length);
        if(ar2.indexOf(ar[rand_num]) == -1){
            ar2.push(ar[rand_num]);
        }
    }
    return ar2;
}

function inArray(value, ar){
    for(key in ar){
        if(ar[key] == value){
            return true;
        }
    }
    return false;
}

function refreshLightwindowLinks() {
    if (!myLightWindow) {
        lightwindowInit();
		var links = $$('.'+myLightWindow.options.classNames.standard);
		   links.each(function(link) {
			  if (link.onclick == null) { // the important modification
				 myLightWindow._processLink(link);
			  }
		   });        
    } else {
        var links = $$('.'+myLightWindow.options.classNames.standard);
        links.each(function(link) {
            if (link.onclick == null) { // the important modification
                myLightWindow._processLink(link);
            }
        });
    }
}