/*
 * Global functions and objects loaded after jQuery and before document.ready
 */
var pageRoot = '/';

/**
 * Fix for the IE ClearType bug.
 */
jQuery.fn.fadeTo = function(speed,to,callback) {
    return this.animate({
        opacity: to
    }, speed, function() {
        if (to == 1 && jQuery.browser.msie)
            this.style.removeAttribute('filter');
            if (jQuery.isFunction(callback))
                callback();
    });
};


/**
 * Parses an URI. If no URI is passed, it will parse the current location.
 * @return Object An object containing the original path (obj.original) and the actual client path (obj.client). They are set false if their data can not be parsed.
 */
function parsePaths(pUri) {
    var rootURI;
    var path;
    var hash;
    if(pUri) {
        var pattern = '((https?)://([^/]+)){0,1}/([^#]+)?(#(.*))?';
        var regexp = new RegExp(pattern);
        var result = regexp.exec(pUri);

        if(result) {
            rootURI = result[1] + pageRoot;
            path = result[4].replace(pageRoot.substr(1), "");
            hash = result[6];
        }
        else {
            return null;
        }
    }
    else {
        rootURI = window.location.protocol + "//" + window.location.host;
        path = window.location.pathname.replace(pageRoot, "");
        hash = window.location.hash.substr(1);
    }


    // Parse the actual path
    var original = new Object();
    if(path) {
        var originalPieces = path.split('/');
        if(originalPieces[originalPieces.length-1] == "") {
            originalPieces.pop();
        }
        original.root = rootURI;
        original.language = originalPieces[0];
        original.page = originalPieces[1];
        original.extra = originalPieces.slice(2);
    }
    else {
        original.root = false;
        original.language = false;
        original.page = false;
        original.extra = false;
    }


    // Parse the actual path
    var client = new Object();
    if(hash) {
        var clientPieces = hash.split('/');
        if(clientPieces[clientPieces.length-1] == "") {
            clientPieces.pop();
        }
        client.root = rootURI;
        client.page = clientPieces[0];
        client.extra = clientPieces.slice(1);
    }
    else {
        client.root = false;
        client.page = false;
        client.extra = false;
    }

    // Create an object to return
    var output = new Object();
    output.original = original;
    output.client = client;

    return output;
}

/**
 *
 */
function showLoading(pElement, hPosition, vPosition) {
    // Get the target element into a jQuery object
    var jTarget;
    if(typeof pElement != "jQuery") {
        jTarget = $(pElement);
    }
    else {
        jTarget = pElement;
    }

    // Set the starting position of the image
    var newPosition = jTarget.offset();

    // Add the horizontal position
    var integer;
    if(hPosition!=null) {
        switch(hPosition) {
            case "right":
                newPosition.left += jTarget.width() - 50;
                break;
            case "center":
                newPosition.left += (jTarget.width() / 2) - 25;
                break;
            case "left":
                break;
            default:
                // See if it is a number
                integer = parseInt(hPosition);
                if(integer && integer != NaN) {
                    //alert('Hor: ' + integer);
                    if(integer < 0) {
                        newPosition.left += (jTarget.width() - 50) + integer;
                    }
                    else {
                        newPosition.left += integer;
                    }
                    
                }
                break;
        }
    }

    // Add the vertical position
    if(vPosition!=null) {
        switch(vPosition) {
            case "bottom":
                newPosition.top += jTarget.height() - 50;
                break;
            case "middle":
                newPosition.top += (jTarget.height() / 2) - 25;
                break;
            case "top":
            default:
                integer = parseInt(vPosition);
                if(integer && integer != NaN) {
                    //alert('Ver: ' + integer);
                    if(integer < 0) {
                        newPosition.top += (jTarget.height() - 50) + integer;
                    }
                    else {
                        newPosition.top += integer;
                    }

                }
                break;
        }
    }

    // Create the overlay
    var newElem = document.createElement('img');
    var jContainer = $(newElem);

    jContainer.hide()
              .load(function() { $(this).fadeIn(500); })
              .attr('loadBar', 'true')
              .attr('src', pageRoot + 'images/ui/loading.gif')
              .attr('alt', 'Loading...')
              .css('position', 'absolute')
              .css('height', '50px')
              .css('width', '50px')
              .css('top', newPosition.top + "px")
              .css('left', newPosition.left + "px")
              .css('bottom', '0')
              .css('right', '0')
              .css('z-index', '100');

    // Append the overlay to the target
    $("body").append(jContainer);
}


function hideLoading() {
    $('img[loadBar=true]').remove();
}

/**
 * Variables and functions to control the Contact Form
 */
var ContactForm = {
    /**
     * Default form values.
     * A false value means that the field needs to be filled before the form
     * is submitted.
     */
    'defaultValues' : {
        'Name' : false,
        'Email' : false,
        'Subject' : 'No subject',
        'Message' : false
    },

    /**
     * Initializes the mail form.
     * Interveenes when the form is submitted.
     */
    'initialize' : function(pExtra) {
        // Set the contact form submit event
        $("#ContactForm").submit(function(event) {
            event.preventDefault();

            ContactForm.process();
        });
    },

    'process' : function() {
        var values = [
            {'Key':'Name', 'Value':$("#ContactForm_Name input:first").val()},
            {'Key':'Email', 'Value':$("#ContactForm_Email input:first").val()},
            {'Key':'Subject', 'Value':$("#ContactForm_Subject input:first").val()},
            {'Key':'Message', 'Value':$("#ContactForm_Message textarea:first").val()}
        ];
        // Check all values
        var valid = true;
        for(var i = 0; i < values.length; i++) {
            if(!values[i].Value || values[i].Value.length == 0) { // Invalid
                if(ContactForm.defaultValues[values[i].Key]) {
                    values[i].Value = ContactForm.defaultValues[values[i].Key];
                }
                else {
                    // Add the Invalid class to the label.
                    $("#ContactForm_" + values[i].Key +" label:first").addClass('Invalid');
                    valid = false;
                }
            }
        }

        // Do stuff
        if(valid) {
            // Compile a key/value list
            var postData = {
                IsPosted : 'True'
            };
            for(var i = 0; i < values.length; ++i) {
                postData[values[i].Key] = values[i].Value;
            }

            // Disable the form and show the load thing
            showLoading($('#ContactForm'), 'center', 'middle');
            $("#ContactForm_Submit").attr('disabled', 'true');
            $("#ContactForm").fadeTo(500, 0.25);

            // Send the thing
            $.post(pageRoot + 'en/contact/?ajax=true', postData, function(data, textStatus) {
                hideLoading();

                if(textStatus == "success"){
                    if(data == "success") {
                        $("#ContactForm").fadeTo(250, 0).slideUp(1000, function() { $(this).remove(); })
                        $("#ContactForm_Header").html(lang['Contact_Message_Header_Sent']);
                        $("#ContactForm_Subheader").html(lang['Contact_Message_Subheader_Success']);
                        $("#ContactForm_ErrorMessage").html(lang['Contact_Message_ErrorMessage_Success']).fadeIn(250);
                    }
                    else {
                        $("#ContactForm").fadeTo(250, 1);
                        $("#ContactForm_Submit").removeAttr('disabled');
                        $("#ContactForm_Subheader").html(lang['Contact_Message_Subheader_Error']);
                        $("#ContactForm_ErrorMessage").html(lang['Contact_Message_ErrorMessage_SendFailed']).fadeIn(250);
                    }
                }
                else {
                    $("#ContactForm").fadeTo(250, 1);
                    $("#ContactForm_Submit").removeAttr('disabled');
                    $("#ContactForm_Subheader").html(lang['Contact_Message_Subheader_Error']);
                    $("#ContactForm_ErrorMessage").html(lang['Contact_Message_ErrorMessage_SendFailed']).fadeIn(250);
                }
                
                
            }, 'text');
        }
        else{
            $("#ContactForm").fadeTo(250, 1);
            $("#ContactForm_Submit").removeAttr('disabled');
            $("#ContactForm_Subheader").html(lang['Contact_Message_Subheader_Error']);
            $("#ContactForm_ErrorMessage").html(lang['Contact_Message_ErrorMessage_FieldsMissing'])
                                          .fadeIn(250);
        }
    }
};

function showGoogleMap() {
    var jContainer = $('#InnerContent');

    // Create the IFrame
    var newIFrame = document.createElement('iframe');
    var jIFrame = $(newIFrame);
        jIFrame.css('width', '580px')
               .css('height', '350px')
               .attr('frameborder', '0')
               .attr('scrolling', 'no')
               .attr('marginheight', '0')
               .attr('marginwidth', '0')
               .attr('src', 'http://maps.google.com/maps/ms?hl=enie=UTF8&source=embed&msa=0&msid=115346475224903657738.00046b62e5333ad27087b&ll=64.100156,-21.373902&spn=0.462849,2.488403&output=embed');

    // Create the link container
    var newLinkContainer = document.createElement('div');
    var jLinkContainer = $(newLinkContainer);
        jLinkContainer.css('text-align', 'left');

    // Create the fist part of the text
    var linkPrefixSpan = document.createElement('span');
    var jPrefix = $(linkPrefixSpan);
        jPrefix.html(lang['Map_LargerView_Prefix']);

    // Create the last part of the text
    var linkPostfixSpan = document.createElement('span');
    var jPostfix = $(linkPostfixSpan);
        jPostfix.html(lang['Map_LargerView_Postfix']);

    // Create the link
    var newLink = document.createElement('a');
    var jLink = $(newLink);
        jLink.css('color', '#0000FF')
             .css('text-align', 'left')
             .html(lang['Map_LargerView_Link'])
             .attr('href', 'http://maps.google.com/maps/ms?hl=en&ie=UTF8&source=embed&msa=0&msid=115346475224903657738.00046b62e5333ad27087b&ll=64.100156,-21.373902&spn=0.462849,2.488403');

    // Assemble all of it
    jLinkContainer.append(jPrefix).append(jLink).append(jPostfix);
    jContainer.append(jIFrame).append(jLinkContainer);
}