
/**
 * this variable should be changed to whatever
 * url will be handeling ajax requests for the entire
 * 5 step process
 */
var posturl = "process.ashx";

$(document).ready(function() {



    switch (step) {
        case "1":
            setDefaultMarketList();

            // listen for clicks on remove links
            $("#reslist a").click(removeMarket);

            disableOtherSteps();

            /**
            * check to see if the user can proceed on to step 2
            */


            $('#submit a').click(function() {
                var ret = false;
                var urlstr = posturl + '?step=1';
                var postdata = 'totalselmarkets=1';
                //$.ajax({async: false, type: "POST", url: urlstr, data: postdata, dataType:"json"});                
                $.ajax({ async: false, type: "POST", url: urlstr, data: postdata, dataType: "json", success: onSuccess });

                function onSuccess(data, status) {
                    if (parseInt(data.totalmarkets) > 0) {
                        ret = true;
                    }
                }

                if (ret == false) {
                    alert("You must select at least one market to proceed.");
                }

                return ret;
            });

            break;

        case "2":
            investmentMenus();
            rightNavigation(".loannav");

            disableOtherSteps();

            break;

        case "3":
            industryPopups();

            disableOtherSteps();
            break;

        case "4":
            step4Sortables();

            disableOtherSteps();
            break;

        case "5":
            step5FormHandlers();
            rightNavigation(".stepoverview");

            submitContactInfo();
            disableOtherSteps();
            showWorking();
            break;

        case "6":
            /*franchiseDetPopups();
            resultSelections();*/
            /*
            if (jQuery.browser.msie && !isIEGreaterThan6()) {
            $('a[id*=franchiselogo_]').hover(
            function() {
            if (!$(this).parent().hasClass('resultsel')) {
            $(this).css('backgroundPosition', 'left bottom');
            }
            },
            function() {
            if (!$(this).parent().hasClass('resultsel')) {
            $(this).css('backgroundPosition', 'left top');
            }
            }
            );
            }*/
            franchiseDetPopups();
            setTimeout(adjustButtons, 0);
           
            break;

    /*    case "7":
            franchiseDetPopups();
            setTimeout(adjustButtons, 0);
            break;*/
        case "res":
            franchiseDetPopups();
            //resultSelections();
            rightNavigation(".stepoverview");            
            if (jQuery.browser.msie && !isIEGreaterThan6()) {
            $('a[id*=franchiselogo_]').hover(
            function() {
            if (!$(this).parent().hasClass('resultsel')) {
            $(this).css('backgroundPosition', 'left bottom');
            }
            },
            function() {
            if (!$(this).parent().hasClass('resultsel')) {
            $(this).css('backgroundPosition', 'left top');
            }
            }
            );
            }
            break;

    }

});


 

/**
 * get selected markets from the flash map
 * and send them to narrow down the results
 */
function sendMarkets(state, markets, marketnames)
{
    setCurrentResultsLoading();

    // remove everything from the list and rebuild it
    //$('#reslist').empty();

    // add each market to the selections list
    jQuery.each(marketnames, function(i, market) {
        addMarket(markets[i], market, "");
    });

    // post the selected markets
	$.post(posturl + "?step=1", 'state=' + state + '&markets=' + markets, processMarkets, "json");
    return true;
}

/**
 * process market results
 */
function processMarkets(results)
{
    // update the result counter
    updateCurrentResults(results.totalres);
}

/**
 * add a market to the selections list
 */
function addMarket(id, entry, state)
{
    // only add the market if it hasnt already been selected
    if (!$('#market_' + id).length) {
        $('#nomarkets').remove();
        $('#reslist').append('<li id="market_' + id + '" style="display:none">' + entry + '<a id="remove_' + id + '" class="nohref">remove</a></li>');
        $('#market_' + id).fadeIn();
        $("#reslist a").click(removeMarket);
    }
}

/**
 * remove a market from the selections list
 */
function removeMarket()
{

    setCurrentResultsLoading();

    var marketid = $(this).attr("id").match(/\d+$/);
    $.post(posturl + "?step=1", 'remove=' + marketid,
    function(data) {
        // remove the market list element
        $('#market_' + marketid).fadeOut();

        // update the result count
        $('#market_' + marketid).remove();
        updateCurrentResults(data.totalres);
        setDefaultMarketList();

    },"json");

    return false;
}

/**
 * update the main result count
 */
function updateCurrentResults(total)
{

    totalresults = total;
    if (total == 0 )
    {
        total = "0";
    }
    $('#rescount').html(total);
}

/**
 * checks to see if the market list is empty
 * if it is, it sets a default label
 */
function setDefaultMarketList()
{
    var totalmarkets = $('li[id^="market_"]').length;
    if (!totalmarkets || totalmarkets == 0) {
        $('#reslist').html('<li id="nomarkets" style="display:none">No markets have been selected.</li>');
        $('#nomarkets').fadeIn();
    }
}

/**
 * show a loading gif for when the current result
 * count is being updated
 */
function setCurrentResultsLoading()
{
    updateCurrentResults('<img src="pub/img/bgorange.gif" alt="loading..."/>');
}

/**
 * function to handle animations for the investment
 * menus in step two
 */
function investmentMenus()
{
    $('#networth_opt').css('display', 'block');

    // listen for clicks on any of the options
    $(".optionsnav").click(function() {

        var optlist = $(this).next();

        $('ul[id$=_opt]').each(function(i, element) {

            var id = $(element).attr("id");

            if (id != $(optlist).attr("id")) {
                $(element).slideUp();
                $(element).prev().removeClass('open');
            } else {
                if ($(optlist).css('display') != "none") {
                    $(optlist).slideUp();
                    $(element).prev().removeClass('open');
                } else {
                    $(element).slideDown();
                    $(element).prev().addClass('open');
                }
            }

        });

    });

    // listen for clicks on networth options and update accordingly
    $("a[id*=networth_]").click(function() {
        networth = $(this).attr("id").match(/(\d+)$/)[1];

        $("a[id*=networth_]").removeClass('selected');

        $(this).addClass('selected');

        setCurrentResultsLoading();
        $.post(posturl + "?step=2", 'networth=' + networth, function(data) {
            updateCurrentResults(data.totalres);
        }, "json");

        return false;
    });

    // listen for clicks on available capital options and update accordingly
    $("a[id*=availcap_]").click(function() {
        availcap = $(this).attr("id").match(/(\d+)$/)[1];

        $("a[id*=availcap_]").removeClass('selected');

        $(this).addClass('selected');

        setCurrentResultsLoading();
        $.post(posturl + "?step=2", 'availcap=' + availcap, function(data) {
            updateCurrentResults(data.totalres);
        }, "json");

        return false;
    });

    // listen for clicks on borrowing capacity options and update accordingly
    $("a[id*=borrowingcap_]").click(function() {
        borrowingcap = $(this).attr("id").match(/(\d+)$/)[1];

        $("a[id*=borrowingcap_]").removeClass('selected');

        $(this).addClass('selected');
        blnEmailGuide =  ($('#chkEmailGuide').val() !== null)? true: false;
        setCurrentResultsLoading();
        $.post(posturl + "?step=2", 'borrowingcap=' + borrowingcap + '&chkEmailGuide=' + blnEmailGuide, function(data) {
            updateCurrentResults(data.totalres);
        }, "json");

        return false;
    });

    // listen for clicks on borrowing capacity options and update accordingly
    $("#chkEmailGuide").click(function() {
        blnEmailGuide =  ($('#chkEmailGuide').val() !== null)? true: false;
        setCurrentResultsLoading();
        $.post(posturl + "?step=2", 'chkEmailGuide=' + blnEmailGuide, function(data) {
            updateCurrentResults(data.totalres);
        }, "json");

        return true;
    });

    /**
     * check to see if the user can proceed on to step 3
     */
    $('#submit a').click(function() {

        if ((!networth)||(networth==-1)) {
            alert("Selection of a Net Worth range is required");
        } else if ((!availcap)||(availcap==-1)) {
            alert("Selection of an Available Capital range is required");
        } else if ((!borrowingcap)||(borrowingcap==-1)) {
            alert("Selection of a Borrowing Capacity range is required");
        } else {
            return true;
        }

        return false;
    });

}

/**
 * function to handle toggled navigation on the right
 * column.
 */
function rightNavigation(cssclass)
{
    $(cssclass).click(function() {

        var details = $(this).next();
        var detid = $(details).attr("id");

        $("div.rightnavinfo").each(function(i, element) {

            var id = $(element).attr("id");
			
			if(id == "whatHappens"){
			var firstmarg = 343;
			var secondmarg = 219;
			
				if($.browser.msie == true){
						firstmarg = 338;
						secondmarg = 201;
					
				}
				
				if ($(details).css('display') != "none") {
					$('a#whatHappens').removeClass("nohover");
                    $(".whatHappens").animate({marginTop: firstmarg}, 0);
                } else {
					$('a#whatHappens').addClass("nohover");
                    $(".whatHappens").animate({marginTop: secondmarg}, 0);
                }

				

			}
			
            if (id != detid) {
                $(element).slideUp();
                $(element).prev().removeClass('rightnavopen');
            } else {

                if ($(details).css('display') != "none") {
                    $(details).slideUp();
                    $(element).prev().removeClass('rightnavopen');
                } else {
                    $(element).slideDown();
                    $(element).prev().addClass('rightnavopen');
                }
            }

        });

    });
}

/**
 * handle light boxes in step three for industry selections
 */
function industryPopups()
{
    $('#industrycontainer ul li a').click(function() {
        var parent = $(this).parent();
        var industryid = $(parent).attr("id").match(/(\d+)$/)[1];

        $.post(posturl + "?step=3", 'industryid=' + industryid + '&industrydet=true', industryLightBox, "json");

    });

    function industryLightBox(data)
    {
        $('#indlbtitle').html(data.name);
        $('#indlbbody').html(data.description);

		$('#industrylb').modal({overlayId:'indOverlay', containerId:'indContainer', closeClass:'close'});
    }

    $('li[id*=industry_] input').click(function() {

        var industries = new Array();

        $('li[id*=industry_] input:checked').each(function(i, elem) {
            industries.push($(elem).parent().parent().attr("id").match(/(\d+)$/)[1]);
        });

        setCurrentResultsLoading();
        $.post(posturl + "?step=3", 'industryid=' + industries.join(","), function(data) {
            updateCurrentResults(data.totalres);
        }, "json");
    });

    /**
     * check to see if the user can proceed on to step 3
     */
    $('#submit a').click(function() {

        if ($('li[id*=industry_] input:checked').length == 0) {

            alert("You must choose at least one Industry");
            return false;
        } else if ( totalresults == 0){
            alert("No Matching Opportunities!\n\n Your prior selections, most likely on Step 2 - Availible Capital, \n" + 
            "and your current selections within Industries have resulted in no matching companies.  \n\n" + 
            "Please select additional Industries here or adjust your Availible Capital on Step 2. ");
            return false;
     } else 
       return true;
    });

}

function openModal(dialog)
{
    dialog.overlay.fadeIn(function() {
       dialog.container.fadeIn();
       dialog.data.fadeIn();
    });
}

function closeModal(dialog)
{
    $('.modalCloseImg').fadeOut();
    dialog.data.fadeOut(function() {
        dialog.container.fadeOut(function() {
            dialog.overlay.fadeOut();
            $.modal.close();
        });
    });
}

/**
 * makes the items in step four sortable. Order of items is saved upon clicking
 * continue.
 */
function step4Sortables()
{
    /**
     * listen for mouseover events to support hover
     * on LI elements in IE
     */
    if (jQuery.browser.msie && !isIEGreaterThan6()) {
        $("#moreof li").hover(
            function() {
                $(this).css('backgroundImage', "url('pub/img/gradient/step4rollover.gif')");
            },
            function() {
                $(this).css('backgroundImage', "none");
            }
        );

        $('#lessof li').hover(
            function() {
                $(this).css('backgroundImage', "url('pub/img/gradient/step4rollover.gif')");
            },
            function() {
                $(this).css('backgroundImage', "none");
            }
        );
    }

    var updated = (typeof isdone == undefined) ? false: isdone;

    $("#moreof").sortable({containment:'parent', opacity:'.8', update:isUpdated});
    $("#lessof").sortable({containment:'parent', opacity:'.8', update:isUpdated});

    function isUpdated()
    {
        updated = true;
    }


    /**
     * save the sequence of the moreof/lessof
     * options before leaving the page
     */
    window.onbeforeunload = function(event) {

        var moreof = $('#moreof').sortable("serialize");
        var lessof = $('#lessof').sortable("serialize");

        var postdata = moreof + '&' + lessof;
        var urlstr = posturl + '?step=4';

        $.ajax({async: false, type: "POST", url: urlstr, data: postdata, dataType:"json"});

        // only prompt if nothing has been changed
        if (updated == false) {
            return "You have not changed the order of these options. If you are happy with the order,";
        }

    }

}

/**
 * utility function to see if ie version greater
 * than six is being used
 */
function isIEGreaterThan6()
{
    return (jQuery.browser.msie && jQuery.browser.version.substr(0,1) > 6) ? true : false;
}

/**
 * form handlers for step five should go
 * in this function
 */
function step5FormHandlers()
{
    $('#email').attr('autocomplete', 'off');

    $('#email').change(function() {
        $('#useremail').val($(this).val());
    });

}

function resultSelections()
{
    $('input[id*=franchisesel_]').click(function() {

        var intid = $(this).attr("id").match(/\d+$/)[0];

        var franchise = $('#franchise_' + intid);
        if ($('#resultform input:checked').length > 5){ 
            alert('You may only choose 5 Preliminary Results.');
            return false;
        }

        if ($(franchise).hasClass('resultsel')) {
            $(franchise).removeClass('resultsel');
        } else {
            $(franchise).addClass('resultsel');

        /*    if ($.browser.msie && isIEGreaterThan6) {
                $(franchise).children('.logo').css('backgroundPosition', 'left bottom');
            }*/

        }
    });

    /**
     * save result selections before leaving the page
     */
    $('#submit a').click(function() {

        if ($('#resultform input:checked').length > 0) {
            $('#resultform').submit();
        } else {
            alert("You must choose at least one franchise");
        }
        return false;
    });
}

function franchiseDetPopups()
{
    $('a[id*=franchisedet_]').click(franchisePopups);

    $('a[id*=franchiselogo_]').click(franchisePopups);

            //todo jja remove ??

    function franchisePopups()
    {
        var intid = $(this).attr("id").match(/\d+$/)[0];

        $.post("BrowseHandler.ashx", {franchiseid:intid,franchisedet:true}, franchiseLightBox, "html");

        function franchiseLightBox(data)
        {
            if(data != '')
		        $('#franchiselb').html(data);
            $('#franchiselb').modal({overlayId:'franOverlay', containerId:'franContainer', closeClass:'close'});
        }

        return false;
    }

}
var strHtmlWorking = "<div style=\"height:75px;background-color:#FAB831;\"><img src=\"pub/img/bgorange.gif\" alt=\"loading...\"/><div><div style=\"height:50px;background-color: #343434;\" ><br />One Moment - Targeting the Top Opportunities Based Upon Your Responses</div></div>\n";
                             

function showWorking() {
    $('#waitlb').html(strHtmlWorking);
    $('#waitlb').modal({ overlayId: 'loginOverlay', containerId: 'waitContainer' });
    setTimeout(function() { $.modal.close(); }, 5000); 
    
}
function submitContactInfo() {
    $('#error').css({ display: "none" });

	
   	/**
	  * add a click event listenter to the submit
	  * link so it will submit the form
	  */
	 $('#submit a').click(function () {

			var errors = false;
	     	var fields = new Array();

			$('#error').css({display:"none"});	

		    if ($('#firstname').val().length < 3 || $('#firstname').val().match(/[^a-zA-Z0-9-\.]+/))
			{
				$('#firstname').addClass("error");
				$('#error').css({display:"inline"});	
				errors = true;
			}
			else
			{ 
				$('#firstname').removeClass("error");
			}
			if ($('#lastname').val().length < 3 || $('#lastname').val().match(/[^a-zA-Z0-9-\.]+/))
			{
				$('#lastname').addClass("error");
				$('#error').css({display:"inline"});	
				errors = true;
			}
			else
			{ 
				$('#lastname').removeClass("error");	
			}


			if (!ValidPhone($('#phone').val())) {
			    $('#phone').addClass("error");
			    $('#error').css({ display: "inline" });
			    errors = true;
			}
			else {
			    $('#phone').removeClass("error");
			}

			if (!emailCheck($('#email').val()))
    		{
				$('#email').addClass("error");
				$('#error').css({display:"inline"});	
				errors = true;
			}
			else
			{ 
				$('#email').removeClass("error");
			}

			if (!ValidZip($('#zipcode').val())) {
			    $('#zipcode').addClass("error");
			    $('#error').css({ display: "inline" });
			    errors = true;
			}
			else {
			    $('#zipcode').removeClass("error");
			}
			
			if ($('#userpassword').val().length < 5 )// && ($('#userpassword').val().length != 0 )) 
			{
				$('#userpassword').addClass("error");
				$('#error').css({display:"inline"});	
				errors = true;
			}
			else
			{ 
				$('#userpassword').removeClass("error");
			}

	     $('#contactform input').each(function(i, elem) {

	        var name = $(elem).attr("name");

	        if (name != 'useremail' && $(elem).attr("type") != 'checkbox') {
	             if ($(elem).val() == "") {
	                 errors = true;

	                 fields.push($(elem).prev().html());

	             }
	        }

	     });

	     if (fields.length > 0) {
	        alert("The following fields are required: \r\n" + fields.join('\r\n'));
	     }

		if (errors == false) {
		    $('#contactform').submit();
		}

	 });
}

function adjustButtons()
{
    var leftcolheight = $('#leftcol').height() - 150;
    var css = {position: 'relative', height: leftcolheight}
    $('#buttons').css(css);
    $('.finalbuttons').css('display', 'block');
}

function disableOtherSteps()
{
    var nextstep = parseInt(step) + 1;
    for(nextstep; nextstep < 6; nextstep++)
    {
        if (!$('#step' + nextstep).hasClass('step' + nextstep + '_edit')) {
            $('#step' + nextstep).addClass('disabled').attr("href", "javascript:void(0)");
        }
    }
}
