var oSel = {
    btnSearch: '#btnSearch'
    , ddlStyle: '#ddlStyle'
    , ddlBedroomsMin: '#ddlBedroomsMin'
    , ddlBedroomsMax: '#ddlBedroomsMax'
    , ddlBathroomsMin: '#ddlBathroomsMin'
    , ddlBathroomsMax: '#ddlBathroomsMax'
    , ddlSqFt : '#ddlSqFt'
    , txtPlanName : '#txtPlanName'
    , pnlInstructions: '#pnlInstructions'
    , pnlCollection: '#pnlCollection'
    , pnlResults: '#pnlResults'
    , pnlDetailsWrap: '#pnlDetailsWrap'
    , pnlCompareWrap: '#pnlCompareWrap'
    , fpLoadingWrap: '#fpLoadingWrap'
    , fpLoading: '.fpLoading'
    , tbResults: '#tbResults'
    , h2Collection: '#h2Collection'    
    , h3NumResults: '#h3NumResults'
    , hfPlanName: '#hfPlanName'
    , printPage: '#printPage'
    , emailFriend: '#emailFriend'
    , emailFriendForm: '#emailFriendForm'
    , compare: '.compare'
    , fpResults: '.fpResults'
    , pnlOptionCategoriesWrap: '#pnlOptionCategoriesWrap'
    , ulResults: '.ulResults'
    , h2Region: '#h2Region'
    , subCategories: '.subCategories'
    , selectRegion: '.selectRegion'    
    , pnlRegionPickerWrap: '#pnlRegionPickerWrap'
};
var oConst = {
    Actions: {
        SearchCollections: 'searchCollections'
        , SearchFloorPlans: 'searchFloorPlans'
        , LoadDetails: 'loadDetails'
        , LoadCompare: 'loadCompare'
        , LoadOptionsCategoryList: 'loadOptionsCategoryList'
        , LoadOptionsList: 'loadOptionsList'
    }
    , SearchURL: 'http://globalcontent.ritz-craft.mojoactive.com/shared-resources/floor-plans/search.aspx?callback=?&action='
    , Templates: {
        Collection: {
            Name: 'CollectionResult'
            , Markup: ''
        }
        , FloorPlanResult: {
            Name: 'FloorPlanResult'
            , Markup: ''
        }
        , FloorPlanDetails: {
            Name: 'FloorPlanDetails'
            , Markup: ''
        }
        , FloorPlanCompare: {
            Name: 'FloorPlanCompare'
            , Markup: ''
        }
        , OptionsCategoryList: {
            Name: 'OptionsCategoryList'
            , Markup: ''
        }
        , OptionsList: {
            Name: 'OptionsList'
            , Markup: ''
        }
        , RegionPicker: {
            Name: 'RegionPicker'
            , Markup: ''
        }
    }
};
var qs = null;

$(function () {
    // define the templates that will be read in on-page
    $.template(oConst.Templates.Collection.Name, oConst.Templates.Collection.Markup);
    $.template(oConst.Templates.FloorPlanResult.Name, oConst.Templates.FloorPlanResult.Markup);
    $.template(oConst.Templates.FloorPlanDetails.Name, oConst.Templates.FloorPlanDetails.Markup);
    $.template(oConst.Templates.FloorPlanCompare.Name, oConst.Templates.FloorPlanCompare.Markup);
    $.template(oConst.Templates.OptionsCategoryList.Name, oConst.Templates.OptionsCategoryList.Markup);
    $.template(oConst.Templates.OptionsList.Name, oConst.Templates.OptionsList.Markup);
    $.template(oConst.Templates.RegionPicker.Name, oConst.Templates.RegionPicker.Markup);

    // define the querystring object so we can quickly get access to vars
    qs = document.queryString();

    // based on the current page, perform setup tasks
    switch (getPageName()) {
        case 'modular-floor-plan.asp':
            // bind the search click action
            $(oSel.btnSearch).click(fpSearchCollections);

            // if there is querystring data, run the search
            fpSearchFloorPlans();

            // capture the enter press in the Plan Name field
            $(oSel.txtPlanName).bind('keypress', function (e) {
                var code = (e.keyCode ? e.keyCode : e.which);
                // if enter pressed
                if (code == 13)
                    fpSearchCollections();
            });

            $(oSel.compare).bind('click', compareFP);
            break;

        case 'modular-floor-plan-details.asp':
            // load the details data
            fpLoadFloorPlanDetails();
            break;

        case 'modular-floor-plan-compare.asp':
            // load the compare data
            fpLoadFloorPlanCompare();
            break;

        case 'modular-floor-plan-options.asp':
            // load the options data
            fpLoadOptionsCategoryList();
            break;

        case 'modular-floor-plan-option-list.asp':
            // load the options data
            fpLoadOptionsList();
            break;

        case 'modular-floor-plan-select-region.asp':
            // load the options data
            fpLoadRegionPicker();
            break;

        default:
            break;
    }
});



/***************************\
* Main Search Button Action *
\***************************/
function fpSearchCollections(e)
{
    // parse sqFt
    var arrSqFt = $(oSel.ddlSqFt).val().split('|');
    // Ajax Query to get data for search
    $.getJSON(oConst.SearchURL + oConst.Actions.SearchCollections, {
        'iSId' : $(oSel.ddlStyle).val()
        , 'iBedMin' : $(oSel.ddlBedroomsMin).val()
        , 'iBedMax' : $(oSel.ddlBedroomsMax).val()
        , 'iBathMin' : $(oSel.ddlBathroomsMin).val()
        , 'iBathMax' : $(oSel.ddlBathroomsMax).val()
        , 'iSqFtMin': arrSqFt[0]
        , 'iSqFtMax': arrSqFt[1]
        , 'sPlanName' : $(oSel.txtPlanName).val()
    }, showCollections);

    // display loading graphic
    $(oSel.pnlCollection).html($(oSel.fpLoadingWrap).html());
}




/**************************\
* View Plans Button Action *
\**************************/
function fpSearchFloorPlans(e)
{
    // if there are querystring values
    if (qs != null && qs.iSId != null ) 
    {
        // first, preselect all the search fields based on QS data
        $(oSel.ddlStyle).val(qs.iSId);
        $(oSel.ddlBedroomsMin).val(qs.iBedMin);
        $(oSel.ddlBedroomsMax).val(qs.iBedMax);
        $(oSel.ddlBathroomsMin).val(qs.iBathMin);
        $(oSel.ddlBathroomsMax).val(qs.iBathMax);
        $(oSel.ddlSqFt).val(qs.iSqFtMin + '|' + qs.iSqFtMax);
        $(oSel.txtPlanName).val(qs.sPlanName);

        // display loading graphic
        $(oSel.fpLoading).show();

        // Ajax Query to get data for search
        $.getJSON(oConst.SearchURL + oConst.Actions.SearchFloorPlans,
            {
                'iSId': qs.iSId
                , 'iBedMin': qs.iBedMin
                , 'iBedMax': qs.iBedMax
                , 'iBathMin': qs.iBathMin
                , 'iBathMax': qs.iBathMax
                , 'iSqFtMin': qs.iSqFtMin
                , 'iSqFtMax': qs.iSqFtMax
                , 'sPlanName': qs.sPlanName
                , 'iCId': qs.iCId
            }, showFloorPlans);
    }
    else 
    {
        $(oSel.pnlInstructions).show();
    }
}




/**************************\
* Details Page Load Action *
\**************************/
function fpLoadFloorPlanDetails(e)
{
    // Ajax Query to get data for search
    $.getJSON(oConst.SearchURL + oConst.Actions.LoadDetails,
        {
            'iSId': qs.iSId
            , 'iBedMin': qs.iBedMin
            , 'iBedMax': qs.iBedMax
            , 'iBathMin': qs.iBathMin
            , 'iBathMax': qs.iBathMax
            , 'iSqFtMin': qs.iSqFtMin
            , 'iSqFtMax': qs.iSqFtMax
            , 'sPlanName': qs.sPlanName
            , 'iCId': qs.iCId
            , 'iFpId': qs.iFpId
        }, showFloorPlanDetails);

    // display loading graphic
    $(oSel.fpLoadingWrap).css('top', '0px');
    $(oSel.fpLoading).show();
}



/**************************\
* Compare Page Load Action *
\**************************/
function fpLoadFloorPlanCompare(e)
{
    // Ajax Query to get data for search
    $.getJSON(oConst.SearchURL + oConst.Actions.LoadCompare,
        {
            'iSId': qs.iSId
            , 'iBedMin': qs.iBedMin
            , 'iBedMax': qs.iBedMax
            , 'iBathMin': qs.iBathMin
            , 'iBathMax': qs.iBathMax
            , 'iSqFtMin': qs.iSqFtMin
            , 'iSqFtMax': qs.iSqFtMax
            , 'sPlanName': qs.sPlanName
            , 'iCId': qs.iCId
            , 'iFpId1': qs.iFpId1
            , 'iFpId2': qs.iFpId2
            , 'iFpId3': qs.iFpId3
        }, showFloorPlanCompare);

    // display loading graphic
    $(oSel.fpLoadingWrap).css('top', '0px');
    $(oSel.fpLoading).show();
}

/**************************\
* Options Page Load Action *
\**************************/
function fpLoadOptionsCategoryList(e) {
    // check for a cookie with the region
    var rId = $.cookie('regionId');
    if (rId != null) 
    {        
        // Ajax Query to get data for search
        $.getJSON(oConst.SearchURL + oConst.Actions.LoadOptionsCategoryList,
        { 'iRId': rId }, showOptionsCategoryList);
    }
    else 
    {
        // load region picker
        showRegionPicker(oSel.pnlOptionCategoriesWrap);       
    }

    // display loading graphic
    $(oSel.fpLoadingWrap).css('top', '0px');
    $(oSel.fpLoading).show();
}

/*******************************\
* Options List Page Load Action *
\*******************************/
function fpLoadOptionsList(e) {
    // check for a cookie with the region
    var rId = $.cookie('regionId');
    if (rId != null && qs.iOcId != null) 
    {        
        // Ajax Query to get data for search
        $.getJSON(oConst.SearchURL + oConst.Actions.LoadOptionsList,
        {   
            'iRId': rId
            , 'iOcId': qs.iOcId
        }, showOptionsList);
    }
    else 
    {
        // load region picker
        window.location.href = '/modular-floor-plan-options.asp';        
    }

    // display loading graphic
    $(oSel.fpLoadingWrap).css('top', '0px');
    $(oSel.fpLoading).show();
}

function fpLoadRegionPicker(e) {
    showRegionPicker(oSel.pnlRegionPickerWrap);
}


/**************************************************\
* Show collections - process collections json data *
*                                                  *
* Dara Format: {                                   *
*                "name": ""                        *
*                , "desc": ""                      *
*                , "img": ""                       *
*                , "numResults": ""                *
*                , "href": ""                      *
*              }                                   *
\**************************************************/
function showCollections(json)
{
    // get the total number of results
    var iTotal = 0;
    for (var i = 0; i < json.length; i++)
        iTotal += parseInt(json[i].numResults);

    // create the title
    if (iTotal > 0)
        $(oSel.pnlCollection).html('<h2>' + iTotal + ' Homes Found... <span style="font-size:0.8em;">Select a Collection</span></h2>');
    else
        $(oSel.pnlCollection).html('<h2>' + iTotal + ' Homes Found... <span style="font-size:0.7em;">Please change your criteria above.</span></h2>')

    // get the base html for the data, and insert clearing divs after every other item
        $(oSel.pnlCollection).append($.tmpl(oConst.Templates.Collection.Name, json));

    // add the results to the panel and one final clearing div
    $('.collection:odd', oSel.pnlCollection).after('<div class="clr"></div>');
    $(oSel.pnlCollection).append('<div class="clr"></div>');

    // show the collections data
    $(oSel.pnlCollection).slideDown(500);
}


function showFloorPlans(json) 
{
    // get the total number of results
    var iTotal = 0;
    for (var i = 0; i < json.length; i++)
        iTotal += parseInt(json[i].numResults);

    // create the title
    $(oSel.h2Collection).html(json.collection);
    $(oSel.h3NumResults).html('Viewing ' + json.floorplans.length + ' floor plans that meet your criteria.');
    
    // get the base html for the data, and insert clearing divs after every other item
    $(oSel.tbResults).append($.tmpl(oConst.Templates.FloorPlanResult.Name, json.floorplans));

    // show the collections data
    $(oSel.pnlResults).show().slideDown(500);

    // hide loading graphic
    $(oSel.fpLoading).hide();
	
	// sort table columns
	$(oSel.fpResults).tablesorter({
		headers: { 
			0: { sorter: false }, 
			1: { sorter: false },
			5: { sorter: false },
			6: { sorter: false }
			} 
		});
}


function showFloorPlanDetails(json) 
{
    // create the title
    $(oSel.pnlDetailsWrap).append($.tmpl(oConst.Templates.FloorPlanDetails.Name, json));

    // show the collections data
    $(oSel.pnlDetailsWrap).slideDown(500);

    // hide loading graphic
    $(oSel.fpLoading).hide();

    // make the tabs work
    $("#tabs").tabs();

    // update the hidden field that contains the plan name
    $(oSel.hfPlanName).val(json.collection + ': ' + json.name);

    // make the popup for larger images work
    $("a[rel^='prettyPhoto']").prettyPhoto();

    // bind the email a friend form click
    $(oSel.emailFriend).click(function (e) {
        //$(oSel.emailFriendForm).slideDown();
        return false;
    });

    // bind the email a friend form click
    $(oSel.printPage).click(function (e) { window.print(); });


    var rId = $.cookie('regionId');
    if (rId == null)
    {
        // load region picker        
        showRegionPicker(oSel.pnlRegionPickerWrap);
    }
}


function showFloorPlanCompare(json) 
{
    // create the title
    $(oSel.pnlCompareWrap).append($.tmpl(oConst.Templates.FloorPlanCompare.Name, json));

    // Hide the 3rd column if only 2 homes compared, and make each col 50% width
    if (qs.iFpId3 == undefined) {
        $('.fpCompare tr').each(function (i, tr) {
            $('>td', tr).eq(2).hide();
        });

        $('.fpCompare td').css('width', '50%');
    }
    else {
        $('.fpCompare td').css('width', '30%');
    }
        

    // show the collections data
    $(oSel.pnlCompareWrap).slideDown(500);

    // hide loading graphic
    $(oSel.fpLoading).hide();
}


function compareFP() 
{
    // get selected items
    var arrChk = $('.fpCompare:checked');

    // length check, if bad, alert, else navigate to compare
    if (arrChk.length != 2 && arrChk.length != 3)
        alert('Please select 2 to 3 floor plans to compare');        
    else 
    {
        // build out the querystring
        var sQs = window.location.search + '&iFpId1=' + arrChk.eq(0).val() + '&iFpId2=' + arrChk.eq(1).val();
        if (arrChk.length == 3) sQs += '&iFpId3=' + arrChk.eq(2).val();
        
        // navigate to compare page
        window.location = '/modular-floor-plan-compare.asp' + sQs;
    }
    return false;
}


function showOptionsCategoryList(json) {
    // create the title
    $(oSel.h2Region).html(json.region);

    // bind the data
    $(oSel.ulResults).append($.tmpl(oConst.Templates.OptionsCategoryList.Name, json.optionCategories));

    var NumCols = 2;
    var Width = 652;
    
    // now get a count of the links we need to work with
    var iNumLinks = $('>li', oSel.ulResults).length,
        iNumLiPerCol = parseInt(iNumLinks / NumCols),
        iNumLiPerColRemainder = iNumLinks % NumCols;

    // create the mega menu
    var oCategoryList = $('<div class="categoryList">');  

    // build out the columns of LIs
    for (var i = 0; i < NumCols; i++) {
        // make a new column and set its styling
        var oCol = $('<ul>');
        $(oCol).css({
            width: parseInt(Width / NumCols) + 'px'
        });

        // add the links to the new ul
        for (var j = 0; j < iNumLiPerCol; j++)
            $(oCol).append($('li', oSel.ulResults).eq(0).remove());

        // if we need to add a few additional links to the first few cols
        if (iNumLiPerColRemainder > 0) {
            $(oCol).append($('li', oSel.ulResults).eq(0).remove())
            iNumLiPerColRemainder--;
        }

        // add the new column
        $(oCategoryList).append(oCol);
    }

    // add a clearing div
    // add the custom clickable nav services content
    // add a clearing div
    $(oCategoryList).append($('<div class="clr">'));

    $(oSel.ulResults).hide();
    $(oSel.pnlOptionCategoriesWrap).append(oCategoryList);
   
    // hide loading graphic
    $(oSel.fpLoading).hide();
}


function showOptionsList(json) {
    // create the title
    $(oSel.h2Region).html(json.region+" Options - "+json.catName);

    // bind the data
    $(oSel.subCategories).append($.tmpl(oConst.Templates.OptionsList.Name, json.optionCategories));

    // pop open option photos in a larger image
    $("a[rel^='prettyPhoto']").prettyPhoto();

    // hide loading graphic
    $(oSel.fpLoading).hide();
}


function showRegionPicker(sel) 
{
    // show region picker inside the selector passed in
    $(sel).html($.tmpl(oConst.Templates.RegionPicker.Name, null));
    // hide loading graphic
    $(oSel.fpLoadingWrap).hide();

    $(oSel.selectRegion).click(selectRegion);
}



/*******************\
* Utility Functions *
\*******************/

function selectRegion(e) {
    if ($(this).hasClass("NE"))
        $.cookie('regionId', '1', { expires: 7 });
    else if ($(this).hasClass("SE"))
        $.cookie('regionId', '2', { expires: 7 });
    else if ($(this).hasClass("MW"))
        $.cookie('regionId', '3', { expires: 7 });

    window.location.href = '/modular-floor-plan-options.asp';
    return false;
}

// returns the name of the current page w/ file extension in all lower case
function getPageName()
{
    // get the url and return only the values after the last "/"
    var href = location.href.split(/[\/\\]/);
    href = href[href.length - 1].toLowerCase();

    // make sure there are no querystring values attached
    href = href.split('?')[0];

    // return the result
    return href;
}

if (!document.queryString) document.queryString = function () 
{
    if (this.URL.indexOf("?") != -1)
    {
        var b = this.URL.substring(this.URL.indexOf("?") + 1).split('#')[0].split("&"), f = {}, x, y;
        for (x in b) f[(y = b[x].split("="))[0]] = y[1];
        return f;
    } 
    else 
    {
        return null;
    }
}



// email validation function
function validate() {
    var msgStr = ""
    var frm = document.emailAFriend
    var pattern = /^.+@.+\..{2,}$/;

    if (frm.name.value == "") {
        msgStr += "Please enter your name.\n";
        frm.name.focus();
    }

    if (frm.email.value == "") {
        msgStr += "Please enter your email address.\n";
        frm.email.focus();
    }
    else if (!(pattern(frm.email.value))) {
        msgStr += "Please enter a valid email address.\n";
        frm.email.focus();
    }

    if (frm.friendsemail.value == "") {
        msgStr += "Please enter your friends email address.\n"
        frm.friendsemail.focus();
    }
    else if (!(pattern(frm.friendsemail.value))) {
        msgStr += "Please enter a valid friends email address.\n";
        frm.friendsemail.focus();
    }

    if (msgStr == "") {
        return true;
    }
    else {
        alert(msgStr);
        return false;
    }
}
