/*
Copyright 2009 Rowdy Labs LLC, ALL RIGHTS RESERVED

 This code is not to be distributed or used unless 
    distributor or user has as separate license permitting
    them to do so. (Provided upon full payment).
*/

var Points = {};    //table matching names of items with point values
var errorCount = 0; //presubmission error counter

//make string safe for JS
function sanitize(str){
    return str.replace(/[^0-9A-Za-z]/g, '_');
}


//
//
// Field Verification
//
//

//verify only digits
function keyupNumCheck(item){
    item.value=item.value.replace(/[^0-9]/g, '');
}

//verify only digits or letters
function keyupAlphanumCheck(item){
    item.value=item.value.replace(/[^0-9A-Za-z]/g, '');
}



//
//
//  Page Generation
//
//

// generate HTML for room headers
function roomHTML(name){
    return  '<tr><td><div>Room: ' + name + '</div></td></tr>'
}

// generate html for furniture cat
function itemHTML(itemName){
    return '<tr><td><input id="" class="furnQty"  name="'+sanitize(itemName)+'" value="" type="text" size="4" onKeyUp="keyupNumCheck(this);calcTotalPoints();"><label class="itemDesc">'+ itemName + "</label></td></tr>";
}

//
//
// Pre Submission error checking
//
//

// returns the error when regex is not matchted in str
function checkText(str,regex,error){
    var index = str.search(regex);
    if(index == -1){
        return error;
    }   
    else { 
        return "";
    }
}

// resets error status
function clearSubmitErrors(){
    $('#submitErrors').html('');
    $('#errorHeader').hide();
    $('#errorDetail').hide();
    errorCount = 0;
}

//puts errors in error table if they exist
function warnOnBadField(str, regex, error){
    var s = checkText(str, regex, error);
    if(s.length > 0)
    {
        $('#errorHeader').show();
        $('#errorDetail').show();
        $('#submitErrors').append("<li class='errorLine'>"+s+"</li>");
        errorCount++;
        return true;
    }
    return false;
}

function checkForErrors(){
    var AtLeastOneChar = '[a-zA-Z0-9]+';
    var Zip = '[a-zA-Z0-9]{5}';
    var Email = '[A-Za-z0-9._%+-]+@[A-Z0-9a-z.-]+[.][A-Za-z]{2,4}'
    warnOnBadField($('#moveDate').val(), AtLeastOneChar,  "Move date is a required field");
    warnOnBadField($('#custName').val(), AtLeastOneChar,  "Customer name is a required feild");
    warnOnBadField($('#phone').val(), AtLeastOneChar,  "Phone number is a required feild");
    warnOnBadField($('#emailAddress').val(), Email,  "Email is a required field (example: myemail@gmail.com)|"+$('#emailAddress').val());
    warnOnBadField($('#startStreet').val(), AtLeastOneChar,  "Starting Street Address is a required field");
    warnOnBadField($('#startCity').val(), AtLeastOneChar,  "Starting City is a required field");
    warnOnBadField($('#startState').val(), AtLeastOneChar,  "Starting State is a required field (example: GA, CA, NY)");
    if(!warnOnBadField($('#startZip').val(), AtLeastOneChar,  "Starting Zip Code a required field (e.g. 30309)"))
    {
        warnOnBadField($('#startZip').val(), Zip,  "Starting Zip Code must be 5 letters or numbers (e.g. 30309)")
    }
    warnOnBadField($('#startDescription').val(), AtLeastOneChar,  "Description of Start Location is a required field");
    warnOnBadField($('#endStreet').val(), AtLeastOneChar,  "Ending Street Address is a required field");
    warnOnBadField($('#endCity').val(), AtLeastOneChar,  "Ending City is a required field");
    warnOnBadField($('#endState').val(), AtLeastOneChar,  "Ending State is a required field (example: GA, CA, NY)");
    if(!warnOnBadField($('#endZip').val(), AtLeastOneChar,  "Ending Zip Code a required field (e.g. 30309)"))
    {
        warnOnBadField($('#endZip').val(), Zip,  "Ending Zip Code must be 5 letters or numbers (e.g. 30309)")
    }
    warnOnBadField($('#endDescription').val(), AtLeastOneChar,  "Description of End Location is a required field");
    warnOnBadField($('#foundHow').val(), AtLeastOneChar,  "How did you find us is a required field");
}


//
//
//  Real time page calculations
//
//


//calculates the total point value and displays it on the page
function calcTotalPoints(){
    var totalPoints = 0;
    for(var i=0;i< $(".furnQty").length;i++){
        var item = $(".furnQty")[i];
        var qty = parseInt( item.value );
        if ( qty > 0)
        {
            totalPoints += (qty * Points[item.name]);
        }
    }

    //get the custom items 
    for(var i=1;i<5;i++){
        var qSel = "#ciq"+i;
        var qItem = $(qSel);
        var qty = parseInt(qItem.val());
        
        var pSel = "#cip"+i;
        var pItem = $(pSel);
        var pts = parseInt(pItem.val()); 
        
        var tVal = qty * pts;
        if ( tVal > 0 )
        {
            totalPoints += tVal;
        }
    }
    $("#totalPoints").html(''+totalPoints);
}

//
//
//  Form Submission
//
//

//concatenates all the fields of the page into a pretty text blurb
function generateEmailBody(){
    var text  =   "Detailed Quote Summary";
        text += "\n----------------------";
        text += "\nTotal Points:   " + $("#totalPoints").text();
        text += "\nMove Date:      " + $("#moveDate").val();
        text += "\nName:           " + $("#custName").val();
        text += "\nStarting Zip:   " + $("#startZip").val();
        text += "\nEnding Zip:     " + $("#endZip").val();
        text += "\nPhone:          " + $("#phone").val();
        text += "\nEmail:          " + $("#emailAddress").val();
        text += "\nContact by:     " + $("#contactMethod").val();
        text += "\nContact time:   " + $("#contactTime").val();
        text += "\nNew Quote:      " + $("#isNewQuote").text();
        text += "\n";
        text += "\n";
        text += "\nStart Loc Description";
        text += "\n---------------------";
        text += "\nStreet Address: " + $("#startStreet").val();
        text += "\nCity:           " + $("#startCity").val();
        text += "\nState:          " + $("#startState").val();
        text += "\nZip:            " + $("#startZip").val();
        text += "\nDesc:           " + $("#startDescription").val();
        text += "\n";
        text += "\n";
        text += "\nEnd Loc Description";
        text += "\n-------------------";
        text += "\nStreet Address: " + $("#endStreet").val();
        text += "\nCity:           " + $("#endCity").val();
        text += "\nState:          " + $("#endState").val();
        text += "\nZip:            " + $("#endZip").val();
        text += "\nDesc:           " + $("#endDescription").val();
        text += "\n";
        text += "\n";
        text += "\nStops along the way";
        text += "\n--------------------";
        text += "\nStops:          " + $("#stops").val();
        text += "\n";
        text += "\n";
        text += "\nFurniture Listing Detail";
        text += "\n--------------------";
        text += "\nTotal Points:   " + $("#totalPoints").text();
        for(var i=0;i< $(".furnQty").length;i++){
            var item = $(".furnQty")[i];
            var qty = parseInt( item.value );
            if ( qty > 0)
            {
                text += "\n" + qty + " X " + item.name;
            }
        }
        for(var i=1;i<5;i++){
            var qSel = "#ciq"+i;
            var qItem = $(qSel);
            
            var pSel = "#cip"+i;
            var pItem = $(pSel);
            
            var dSel = "#cid"+i;
            var dItem = $(dSel);
            
            if(parseInt(qItem.val())<=0) continue;

            text += "\n"+qItem.val()+" X [Custom]" + dItem.val() + " @ " + pItem.val() + " points";
             
        }
        text += "\n";
        text += "\n";
        text += "\nHow Did They Find Us?";
        text += "\n-------------------";
        text += "\nSource:         " + $("#foundHow").val();
        text += "\nSource Detail:  " + $("#foundHowDetail").val();
        text += "\n";
        text += "\n";
        text += "\n";

        return text;
        
}


//submits all data to the server for further processing
function submitToServer(){
    $('#theReport').val(generateEmailBody());
  
    $.post("scripts/mailMoveForm.php",{"theEmail":$("#emailAddress").val(),"theReport":generateEmailBody()},
            function(data){
               $('#theForm').html(data); 
            });

}


//goes through all required fields, verifies they exist and have 
//    properly formatted data, displays error messages if they do not, 
//    submits if they do
function verifyAndSubmit(){
    clearSubmitErrors();
    checkForErrors();
    if (errorCount == 0)
    {
        submitToServer();
    }
}


//
//
//  Startup Code
//
//

//initializer function, run after DOM load
$(function (){
        clearSubmitErrors();
        
        for( var roomNumber =0; roomNumber < FurniturePoints.Rooms.length; roomNumber++)
        {
            $(roomHTML(FurniturePoints.Rooms[roomNumber].name)).insertBefore("#TableEntryEnd");
            for( var itemNumber = 0; itemNumber< FurniturePoints.Rooms[roomNumber].items.length; itemNumber++)
            {
                var item = FurniturePoints.Rooms[roomNumber].items[itemNumber];
                $(itemHTML(item.name)).insertBefore("#TableEntryEnd");
                Points[sanitize(item.name)]=item.points;
            }
        }

});

