/*
* Variable's name format is {{a-zA-Z0-9_}} (Django template variables' format)
* and cannot begin with numbers
*
* ctx is an object with properties' names matching variables' names in input string
* i.e: (using object literal to define the context object): 
*    var myStr = "<p>Example string with {{variable}}.</p>";
*    var myContext = {variable : "variable text"};
*    alert(myStr.format(myContext) == "<p>Example string with variable text.</p>");
*
* ctx could be also a JSON string. In this case the object is constructed from the string.
* Variables not existing in context are replaced with an empty string
*/
String.prototype.format = function(ctx)
{
    var str = this;
                
    var varDefinitionRE = /{{\s*[a-zA-Z0-9_]+\s*}}/g;
    var varNameRE = /{{\s*([a-zA-Z0-9_]+)\s*}}/;

    var matches = str.match(varDefinitionRE);

    if(matches)
    {
        if(typeof ctx == "string") { ctx = eval("({{jsonString}})".format({jsonString: ctx})); }

        for(var i = 0;i < matches.length;i++)
        {
            var key = matches[i].match(varNameRE)[1];
            if(!ctx[key]) { ctx[key] = ""; }
            str = str.replace(matches[i], ctx[key]);
        }
    }
                
    return str;
}

String.prototype.capitalize = function()
{
    var str = this;
    while(str.search("  ") != -1)
        str = str.replace("  ", " ");
    strArray = str.split(" ");
    for(i=0,l=strArray.length;i<l;i++)
        strArray[i] = strArray[i].slice(0, 1).toUpperCase() + strArray[i].slice(1, strArray[i].length)
    return strArray.join(" ");
}


function check(target, id)
{
    // Regular Expression matching from
	// http://regexlib.com/UserPatterns.aspx?authorId=1758
    var emailRegExp = /^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$/i;
        
    if(target.val().length == 0)
        return false;
    
    if(id == "email" && !emailRegExp.test(target.val()))
        return false;
        
    return true;
}


function resetContactForm()
{
    var elements = new Array("name", "company", "address", "email", "message");
    for(var i = 0;i<elements.length;i++)
    {
        $("#"+elements[i]).css("border-color", "#424242");
        $("#"+elements[i]).val("");
    }
}

function resetContactUsNowForm()
{
    var elements = new Array("solicitation_number", "contract_number", "company_name", "contact_name", "telephone", "email");
    for(var i = 0;i<elements.length;i++)
    {
        $("#"+elements[i]).css("border-color", "#424242");
        $("#"+elements[i]).val("");
    }
}

function resetRequestAQuoteForm()
{
    var elements = new Array("name", "lastname", "email", "organization", "phone", "origin_city_state", "origin_country", "destination_city_state", "destination_country", "domestic", "international", "description_of_goods");
    for(var i = 0;i<elements.length;i++)
    {
        $("#"+elements[i]).css("border-color", "#424242");
        $("#"+elements[i]).val("");
    }
}

function onContactSubmit()
{
    var Name = $("#name");
    var Company = $("#company");
    var Address = $("#address");
    var Email = $("#email");
    var Message = $("#message");
        
    var formAction = $("#contact_form").attr("action");
    
    var toValidate = Array("name", "company", "address", "email", "message");
    
    var haveErrors = false;
    var errorsOn = new Array();
    
    for(var i = 0;i<toValidate.length;i++)
    {
        var id = toValidate[i];
        var elem = $("#"+id);
        var result = check(elem, id);
        if(!result)
        {
            haveErrors = true;
            errorsOn[errorsOn.length] = id;
            elem.css("border-color", "#A30E0E");
        }
        else
        {
            elem.css("border-color", "#424242");
        }
    }
    
    
    if(haveErrors == true)
    {
        var text = "";
        for(var i = 0;i<errorsOn.length;i++)
            text += "  - " + errorsOn[i].capitalize()+"\n";
        alert("Please, check your input in:\n" + text, "Error");
        return false;
    }
    else
    {
        $.post(formAction,
               {name: Name.val(), company: Company.val(), address: Address.val(), email: Email.val(), message: Message.val() },
               function(data)
               {
                   if(data == 1)
                       alert("Thanks! Your mail has been sent.");
                   else
                       alert("Sorry, your mail could not be sent.\nThere is a problem with our Mail Service by now.\nPlease, try again later or just call us.");
                   resetContactForm();
               }
              );
        return false;
    }
}


function onContactUsNowSubmit()
{
    var SolicitationNumber = $("#solicitation_number");
    var ContractNumber = $("#contract_number");
    var CompanyName = $("#company_name");
    var ContactName =  $("#contact_name");
    var Telephone =  $("#telephone");
    var Email = $("#email");
        
    var formAction = $("#contact_us_now_form").attr("action");
    
    var toValidate = Array("solicitation_number", "contract_number", "company_name", "contact_name", "telephone", "email");
    
    var haveErrors = false;
    var errorsOn = new Array();
    
    for(var i = 0;i<toValidate.length;i++)
    {
        var id = toValidate[i];
        var elem = $("#"+id);
        var result = check(elem, id);
        if(!result)
        {
            haveErrors = true;
            errorsOn[errorsOn.length] = id;
            elem.css("border-color", "#A30E0E");
        }
        else
        {
            elem.css("border-color", "#424242");
        }
    }
    
    
    if(haveErrors == true)
    {
        var text = "";
        for(var i = 0;i<errorsOn.length;i++)
            text += "  - " + errorsOn[i].split("_").join(" ").capitalize()+"\n";
        alert("Please, check your input in:\n" + text, "Error");
        return false;
    }
    else
    {
        $.post(formAction,
               {solicitation_number: SolicitationNumber.val(), contract_number: ContractNumber.val(), company_name: CompanyName.val(), contact_name: ContactName.val(), telephone: Telephone.val(), email: Email.val() },
               function(data)
               {
                   if(data == 1)
                   {
                       alert("Thanks! Your mail has been sent.");
                       $("#login-window p.close-button a").click();
                   }
                   else
                       alert("Sorry, your mail could not be sent.\nThere is a problem with our Mail Service by now.\nPlease, try again later or just call us.");
                   resetContactUsNowForm();
               }
              );
        return false;
    }
}

function onRequestAQuoteSubmit()
{
    var Name = $("#login-window #name");
    var lastname = $("#lastname");
    var email = $("#login-window #email");
    var organization = $("#organization");
    var phone = $("#phone");
    var fax = $("#fax");
    var origin_street_address = $("#origin_street_address");
    var origin_city_state = $("#origin_city_state");
    var origin_zip = $("#origin_zip");
    var origin_country = $("#origin_country");
    var destination_street_address = $("#destination_street_address");
    var destination_city_state = $("#destination_city_state");
    var destination_zip = $("#destination_zip");
    var destination_country = $("#destination_country");
    var domestic = $("#domestic");
    var international = $("#international");
    var description_of_goods = $("#description_of_goods");
    var is_hazardous = $("input:radio[name=is_hazardous]:checked");
    var insurance_required = $("input:radio[name=insurance_required]:checked");
    var value_of_cargo = $("#value_of_cargo");

    var item1_applicability = $("input:radio[name=item1_applicability]:checked");
    var item1_weight = $("#item1_weight");
    var item1_weight_unit = $("#item1_weight_unit");
    var item1_length = $("#item1_length");
    var item1_length_unit = $("#item1_length_unit");
    var item1_width = $("#item1_width");
    var item1_width_unit = $("#item1_width_unit");
    var item1_height = $("#item1_height");
    var item1_height_unit = $("#item1_height_unit");
    var item1_pieces = $("#item1_pieces");
    
    var item2_applicability = $("input:radio[name=item2_applicability]:checked");
    var item2_weight = $("#item2_weight");
    var item2_weight_unit = $("#item2_weight_unit");
    var item2_length = $("#item2_length");
    var item2_length_unit = $("#item2_length_unit");
    var item2_width = $("#item2_width");
    var item2_width_unit = $("#item2_width_unit");
    var item2_height = $("#item2_height");
    var item2_height_unit = $("#item2_height_unit");
    var item2_pieces = $("#item2_pieces");
    
    var item3_applicability = $("input:radio[name=item3_applicability]:checked");
    var item3_weight = $("#item3_weight");
    var item3_weight_unit = $("#item3_weight_unit");
    var item3_length = $("#item3_length");
    var item3_length_unit = $("#item3_length_unit");
    var item3_width = $("#item3_width");
    var item3_width_unit = $("#item3_width_unit");
    var item3_height = $("#item3_height");
    var item3_height_unit = $("#item3_height_unit");
    var item3_pieces = $("#item3_pieces");
    
    var item4_applicability = $("input:radio[name=item4_applicability]:checked");
    var item4_weight = $("#item4_weight");
    var item4_weight_unit = $("#item4_weight_unit");
    var item4_length = $("#item4_length");
    var item4_length_unit = $("#item4_length_unit");
    var item4_width = $("#item4_width");
    var item4_width_unit = $("#item4_width_unit");
    var item4_height = $("#item4_height");
    var item4_height_unit = $("#item4_height_unit");
    var item4_pieces = $("#item4_pieces");
    
    var item5_applicability = $("input:radio[name=item5_applicability]:checked");
    var item5_weight = $("#item5_weight");
    var item5_weight_unit = $("#item5_weight_unit");
    var item5_length = $("#item5_length");
    var item5_length_unit = $("#item5_length_unit");
    var item5_width = $("#item5_width");
    var item5_width_unit = $("#item5_width_unit");
    var item5_height = $("#item5_height");
    var item5_height_unit = $("#item5_height_unit");
    var item5_pieces = $("#item5_pieces");

    var formAction = $("#request_a_quote_form").attr("action");
    
    var toValidate = Array("name", "lastname", "email", "organization", "phone", "origin_city_state", "origin_country", "destination_city_state", "destination_country", "domestic", "international", "description_of_goods");
    
    var haveErrors = false;
    var errorsOn = new Array();
    
    for(var i = 0;i<toValidate.length;i++)
    {
        var id = toValidate[i];
        var elem = $("#login-window #"+id);
        var result = check(elem, id);
        if(!result)
        {
            haveErrors = true;
            errorsOn[errorsOn.length] = id;
            elem.css("border-color", "#A30E0E");
        }
        else
        {
            elem.css("border-color", "#424242");
        }
    }
    
    if(haveErrors == true)
    {
        var text = "";
        for(var i = 0;i<errorsOn.length;i++)
            text += "  - " + errorsOn[i].split("_").join(" ").capitalize()+"\n";
        alert("Please, check your input in:\n" + text, "Error");
        return false;
    }
    else
    {
        $.post(formAction,
               {Name: Name.val(), lastname: lastname.val(), email: email.val(), organization: organization.val(), phone: phone.val(), fax: fax.val(), origin_street_address: origin_street_address.val(), origin_city_state: origin_city_state.val(), origin_zip: origin_zip.val(), origin_country: origin_country.val(), destination_street_address: destination_street_address.val(), destination_city_state: destination_city_state.val(), destination_zip: destination_zip.val(), destination_country: destination_country.val(),domestic: domestic.val(), international: international.val(), description_of_goods: description_of_goods.val(), is_hazardous: is_hazardous.val(), insurance_required: insurance_required.val(), value_of_cargo: value_of_cargo.val(), item1_applicability: item1_applicability.val(), item1_weight: item1_weight.val(), item1_weight_unit: item1_weight_unit.val(), item1_length: item1_length.val(), item1_length_unit: item1_length_unit.val(), item1_width: item1_width.val(), item1_width_unit: item1_width_unit.val(), item1_height: item1_height.val(), item1_height_unit: item1_height_unit.val(), item1_pieces: item1_pieces.val(), item2_applicability: item2_applicability.val(), item2_weight: item2_weight.val(), item2_weight_unit: item2_weight_unit.val(), item2_length: item2_length.val(), item2_length_unit: item2_length_unit.val(), item2_width: item2_width.val(), item2_width_unit: item2_width_unit.val(), item2_height: item2_height.val(), item2_height_unit: item2_height_unit.val(), item2_pieces: item2_pieces.val(), item3_applicability: item3_applicability.val(), item3_weight: item3_weight.val(), item3_weight_unit: item3_weight_unit.val(), item3_length: item3_length.val(), item3_length_unit: item3_length_unit.val(), item3_width: item3_width.val(), item3_width_unit: item3_width_unit.val(), item3_height: item3_height.val(), item3_height_unit: item3_height_unit.val(), item3_pieces: item3_pieces.val(), item4_applicability: item4_applicability.val(), item4_weight: item4_weight.val(), item4_weight_unit: item4_weight_unit.val(), item4_length: item4_length.val(), item4_length_unit: item4_length_unit.val(), item4_width: item4_width.val(), item4_width_unit: item4_width_unit.val(), item4_height: item4_height.val(), item4_height_unit: item4_height_unit.val(), item4_pieces: item4_pieces.val(), item5_applicability: item5_applicability.val(), item5_weight: item5_weight.val(), item5_weight_unit: item5_weight_unit.val(), item5_length: item5_length.val(), item5_length_unit: item5_length_unit.val(), item5_width: item5_width.val(), item5_width_unit: item5_width_unit.val(), item5_height: item5_height.val(), item5_height_unit: item5_height_unit.val(), item5_pieces: item5_pieces.val()},
               function(data)
               {
                   if(data == 1)
                   {
                       alert("Thanks! Your mail has been sent.");
                       $("#login-window p.close-button a").click();
                   }
                   else
                       alert("Sorry, your mail could not be sent.\nThere is a problem with our Mail Service by now.\nPlease, try again later or just call us.");
                   resetContactUsNowForm();
               }
              );
        return false;
    }
}


function rotateSlideshow(index)
{
    clearTimeout(document.timeOutId);
    $("#wrapper #slideshow img").fadeOut(800, function()
    {
        _index = (index < 10) ? "0"+index : index;
        $("#wrapper #slideshow img").attr("src", "/static/images/slides/slide"+_index+".jpg");
        $("#wrapper #slideshow img").fadeIn(800, function()
        {
            $("#wrapper #slideshow img").fadeTo(4400, 1.0, function()
            {
                index = (index == document.slidesCount) ? index  = 1: index = index + 1;
                
                document.timeOutId = window.setTimeout("rotateSlideshow("+ index +")", 0)            
            });
        });
    });
        
    return false;
}

function showLoginWindow()
{
    var requestedURL = $(this).attr("href");
    var urlId = requestedURL.replace("login-", "");
    var target = "#login-window";
    var targetDiv = "#login-window div";    
    var targetSection = "#login-window section";
    
    scrollTop = $(window).scrollTop();
    $(target).css({
                   "width":"100%",
                   "height":$(document).height(),
                   "top": "0"
                   });
    $(targetDiv).css({
                   "top": scrollTop+($(window).height()/2)+"px"
                   });
    var title = $("ul#buttons "+urlId+" span").html();
    var content = document.loginWindowTemplate.format({title: ""+title+""});
    $(targetDiv).html(content);
    $(target).show(0, function() { $(targetDiv).fadeIn(500);});
    $(target+" p.close-button a").click(function() {
                                                    $(targetDiv).fadeOut(500,function() {
                                                                       $(target).hide(0);
                                                                       $(targetDiv).html(""); });
                                                    return false; });
    $(window).scrollTop(scrollTop);
    return false;
}


function showFormWindow()
{
    var requestId = $(this).attr("href").replace("#", "");
    var urlId = "/"+requestId;
    title = requestId.split("-").join(" ").capitalize();
    var target = "#login-window";
    var targetDiv = "#login-window div#floating";    
    var targetSection = "#login-window section";
    
    $.get(urlId, function(data) {
            scrollTop = $(window).scrollTop();
            $(target).css({
                           "width":"100%",
                           "height":$(document).height(),
                           "top": "0"
                           });
            if(requestId == "contact-us-now")
                $(targetDiv).css({
                               "height" : "280px",
                               "width" : "420px",
                               "top": scrollTop+(Math.round($(window).height()/2)-50)+"px",
                               "left": "50%",
                               "margin-left":"-200px"
                               });
            else
            {
                $(targetDiv).css({
                               "height" : Math.round($(window).height()*0.6)+"px",
                               "width" : "480px",
                               "top": scrollTop+(Math.round($(window).height()*0.3))+"px",
                               "left": "50%",
                               "margin-left":"-240px"
                               });
            }
            var content = document.formWindowTemplate.format({title: ""+title+"", content: ""+data+""});
            $(targetDiv).html(content);
            $("#login-window section.form").css({
                               "height" : parseInt($(targetDiv).css("height").replace("px", ""))-40+"px",
                               });
            $(target).show(0, function() { $(targetDiv).fadeIn(500);});
            $(target+" p.close-button a").click(function() {
                                                            $(targetDiv).fadeOut(500,function() {
                                                                               $(target).hide(0);
                                                                               $(targetDiv).html(""); });
                                                            return false; });
            $(window).scrollTop(scrollTop);
    });
    return false;
}

function atReady()
{
    $("#contact_form").submit(onContactSubmit);
    $("#contact_us_now_form").live("submit", onContactUsNowSubmit);
    $("#request_a_quote_form").live("submit", onRequestAQuoteSubmit);
    
    $("#contact-us-now").live("click", showFormWindow);
    $("#request-a-quote").live("click", showFormWindow);
    document.formWindowTemplate = "<p class=\"close-button\"><a href=\"#close\" title=\"Close this Window\">Close [x]</a></p>\n<h4>{{title}}</h4>\n<section class=\"form\">\n{{content}}\n</section>";
    
    $("#login-window div#floating #description_of_goods").live("keyup", function()
                                                                        {
                                                                            var spanId = "#textarea_div span.counter";
                                                                            var content = $.trim($(this).val());
                                                                            var wordsCount = (content == "")
                                                                                             ? 0
                                                                                             : content.split(" ").length;
                                                                            if(wordsCount > 10)
                                                                            {
                                                                                content = content.split(" ").slice(0, 10).join(" ");
                                                                                $(this).val(content);
                                                                            }
                                                                            $(spanId).html((10 - wordsCount) + " words left");
                                                                        });
    
    for(i=1,total=5;i<=total;i++)
    {
        $("#login-window div#floating #item"+i+"_applicability_no").live("click", function()
                                                                                  {
                                                                                    var baseId = $(this).attr("id").split("_")[0];
                                                                                    $("#"+baseId+"_fieldset .item-data-group").css("display", "none");
                                                                                    $("#"+baseId+"_fieldset .item-data-group input, #"+baseId+"_fieldset .item-data-group select").attr("disabled", "disabled");
                                                                                  });
        $("#login-window div#floating #item"+i+"_applicability_yes").live("click", function()
                                                                                  {
                                                                                    var baseId = $(this).attr("id").split("_")[0];
                                                                                    $("#"+baseId+"_fieldset .item-data-group").css("display", "block");
                                                                                    $("#"+baseId+"_fieldset .item-data-group input, #"+baseId+"_fieldset .item-data-group select").removeAttr("disabled");
                                                                                  });
    }
    
    // Slideshow
    document.slidesCount = 0;
	$.get("/information/slides-count", function(data) {document.slidesCount = data;});
    document.timeOutId = window.setTimeout("rotateSlideshow(2)", 5000);
    
    // Floating Windows
    $("#home ul#buttons #e-file a").live("click", showLoginWindow);
    $("#home ul#buttons #track-and-trace a").live("click", showLoginWindow);
    document.loginWindowTemplate = "<p class=\"close-button\"><a href=\"#close\" title=\"Close this Window\">Close [x]</a></p>\n<h4>{{title}}</h4>\n<section><form title=\"Disabled until implemented\"><div><label for=\"username\">Username</label> <input type=\"text\" name=\"username\" id=\"username\" disabled /></div><div><label for=\"password\">Password</label> <input type=\"text\" name=\"password\" id=\"password\" disabled /></div><div id=\"submit_div\"><input type=\"submit\" name=\"submit\" id=\"submit\" value=\"Log in\" disabled /></div></form></section>";
    
    return false;
}

$(document).ready(atReady)


