/*
* Share This Via Email or Social Handler
* Copyright (c) 2009 Andrew Greenstreet | andrewgstreet@gmail.com
* Revision: 1.0
*/

//What view is showing 1st, or now
var shareCurrentTarget;
//Is the form validated
var isVerified = false;


//Called before the share form is submitted
function submitShareForm() {
    //return true;
    var isValid = true;
    if (!validateField($("#fromNameField")[0])) isValid = false;
    if (!validateEmail($("#yourEmailField")[0])) isValid = false;
    if (!validateField($("#friendsNameField")[0])) isValid = false;
    if (!validateEmail($("#friendsEmailField")[0])) isValid = false;

    if (!isVerified) {
        //Double check that the verification image is good
        setFieldToInvalid($("#verifyField")[0]);
        return false;
    }

    if (isValid) {
        $("#previewButton")[0].disbled = true;
        $("#sendButton")[0].disbled = true;
        $("#verifyField")[0].disabled = false;
    }
    if (isValid) {
        var _fromName = $("#fromNameField").val();
        var _fromEmail = $("#yourEmailField").val();
        var _toName = $("#friendsNameField").val();
        var _toEmail = $("#friendsEmailField").val();
        var _personalMessage = $("#personalMessageField").val();
        var _vid = $("#verifyField").val();
        var _preview = $("#previewField").val();
        var _shareUrl = $("#shareUrlField").val();
    }

    $.post("http://es.sidekick.com/enes/utils/shareHandler.ashx", { fromName: _fromName, fromEmail: _fromEmail, toName: _toName, toEmail: _toEmail, personalMessage: _personalMessage, vid: _vid, preview: _preview, shareUrl: _shareUrl }, shareFormSubmitCallback);
    $("#shareResponseContent").html('<img src="http://www.sidekick.com/scripts/tmobile/images/share/loading_animation.gif" />');
    switchSharePanelFromName("response");

    //return isValid;
}

//Called when the shareHandler.ashx responds
function shareFormSubmitCallback(responseText, statusText) {
    $.fn.log(responseText);
    if ($("#previewField")[0].value == "false") {
        if (responseText == "1") {
            //Server Error
            $("#shareResponseContent").html("<p><b>Ocurri\363 un problema al enviar tu mensaje.</b></p><p><br/>Intenta nuevamente m\341s tarde.</p>");
        } else if (responseText == "2") {
            //Invalid session
            $("#shareResponseContent").html("<p><b>\241Uy!</b></p><p><br/>Revisa el n\372mero de verificaci\363n.</p>");
            //Update the verification image
            resetVerification();
        } else {
            //Success
            $("#shareResponseContent").html("<p><b>Gracias.</b></p><p><br/>Se ha enviado tu mensaje.</p>");
            resetForm();
        }
        //swapShareScreens("response");
        switchSharePanelFromName("response");

    } else {
        //Show the preview form
        $('#sharePreviewContent').html(responseText);
        $('#sharePreviewModal').modal(
            {
                closeClass: "modalClose",
                position: ['106px', ]
            }
        );
            switchSharePanelFromName("email");
    }
}

/**  Begin Validation Functions **/

//Validates and Email field
function validateEmail(target) {
    var filter = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i;
    if (!filter.test(target.value) || target.value == "") {
        setFieldToInvalid(target);
        return false;
    }
    setFieldToValid(target);
    return true;
}
//Validates a text field
function validateField(target) {
    if (target.value == "") {
        setFieldToInvalid(target);
        return false;
    }
    setFieldToValid(target);
    return true;
}

function limitField(target, limit) {
    var val = target.value.toString();
    if (val.length == limit) {
        val = val.substring(0, limit);
        target.value = val;
    }
}

/** End Validation Functions **/

//Update the image in the verification field
function resetVerification() {
    $("#botHead")[0].src = "http://es.sidekick.com/enes/utils/verificationimage.ashx?file=" + Math.random() * 10000;
    $("#verifyField")[0].value = "";
    $("#verificationLabel")[0].innerHTML = "Ingresa el n\372mero que aparece a continuaci\363n*";
    isVerified = false;
}

function resetForm() {
    var fromEmail = $("#friendsNameField")[0].value = "";
    var toEmail = $("#friendsEmailField")[0].value = "";
    $("#personalMessageField")[0].value = "";
    resetVerification();
}

//Turns the background of a field to pink to indicated it needs attention
function setFieldToInvalid(target) {
    target.style.backgroundColor = "#FFc6c6";
}
//Turn the background of a field to white, indicating it is good
function setFieldToValid(target) {
    target.style.backgroundColor = "#FFFFFF";
}
//Called on keychanges to the verification field
//Calls the verification handler via ajax to find out if this number if valid
function checkVerifyImage(target) {
    if (target.value.length > 4) {
        isVerified = false;
        $.post("http://es.sidekick.com/enes/utils/checkVerification.ashx", { number: target.value }, checkVerifyImageCallback);
    }
}
//Callback handler for verification request.
function checkVerifyImageCallback(results) {
    if (results == "1") {
        setFieldToInvalid($("#verifyField")[0]);
        $("#verificationLabel")[0].innerHTML = "\241Uy! Intenta nuevamente.";
        resetVerification();
        isVerified = false;
    } else if (results == "2") {
        setFieldToInvalid($("#verifyField")[0]);
        resetVerification();
    } else {
        setFieldToValid($("#verifyField")[0]);
        $("#verificationLabel")[0].innerHTML = "\241Verificaci\363n completa!";
        isVerified = true;
    }
}
//Hide the share this container
function hideShareThis() {
    //$("#shareContainer")[0].style.display = "none";
    $("#shareContainer").fadeOut(500);
    
}
//Call this function to share a specific URL
function shareThisPage(pageUrl, pageTitle) {

    ///<summary>Main Function for Turning on the Share Window<summary>
    ///<param name="pageUrl">Optional argument for the page your wish to share</param>
    ///<param name="pageUrl">Option argument for the title of the page your wish to share</param>
    ///<returns>Nothing</returns>
    //alert("shareThisPage:" + pageUrl);
    if (!pageUrl) {
        pageUrl = document.location;
    }
    positionShareThisPopup();
    switchSharePanelFromName('email');
    $("#shareContainer").fadeIn(500);
    //$("#shareContainer")[0].style.display = "block";
    $("#shareUrlField")[0].value = pageUrl;
    $("#sharePageTitleField")[0].value = pageTitle;
    $("#copyURLField")[0].value = pageUrl;
	//alert("pageUrl:"+pageUrl);
}
//Call this funciton to share a specific video
function shareThisVideo(pageUrl, videoTitle) {
    //TODO Write the code for this
}
//Set the preview mode to on off.
//When set to true, callback from a form submission will show a sample of the email to be sent
//When set to false, callback from a form submission will show a success screen
function setSharePreview(isPreview) {
    $("#previewField")[0].value = isPreview;
}

function copyToClipBoard() {
    //Works in IE only. For Firefox the script must be signed, which this is not.
    var CopiedTxt = $("#copyURLField")[0].value;
    window.clipboardData.setData("Text", CopiedTxt);
}

/**
* Postioning Functions and Handlers
*/
var dimensions = { width: 0, height: 0 };
function setDimensions() {
    if (document.documentElement) {
        dimensions.width = document.documentElement.offsetWidth;
        dimensions.height = document.documentElement.offsetHeight;
    } else if (window.innerWidth && window.innerHeight) {
        dimensions.width = window.innerWidth;
        dimensions.height = window.innerHeight;
    }
}
//User Definable Functions for Positions the Window on Browser Resize
var shareThisLeftPositionFunction;
var shareThisTopPositionFunction;
//User Definable Parameters for setting the absolute position of the form
var shareThisLeftPosition = 0;
var shareThisTopPosition = 0;

function positionShareThisPopup() {
    //Vertical Positioning Functions
    if (shareThisLeftPositionFunction) {
        setShareLeftPosition(shareThisLeftPositionFunction());
    } else if (shareThisLeftPosition) {
        setShareLeftPosition(shareThisLeftPosition);
    }
    //Horizontal Positioning Functions
    if (shareThisTopPositionFunction) {
        setShareTopPosition(shareThisTopPositionFunction());
    } else if (shareThisTopPosition) {
        setShareTopPosition(shareThisTopPosition);
    }
    //$.fn.log("Moving Share Window To: top:" + $('#shareContainer')[0].style.top + " left:" + $('#shareContainer')[0].style.left);
}

function setShareLeftPosition(nX) {
    $('#shareContainer')[0].style.left = nX + "px";
}

function setShareTopPosition(nY) {
    $('#shareContainer')[0].style.top = nY + "px";
}

/** End of Positioning Functions **/

// prepare the share form when the DOM is ready
$(document).ready(function() {
    setDimensions();
    $(window).bind('resize', function() { setDimensions(); positionShareThisPopup(); });
});


/** Panel Switching Functions **/
var currentSelectedShareButton;
var currentSelectedSharePanel;

function switchSharePanelFromName(target) {
    if (currentSelectedSharePanel != undefined) {
        $(currentSelectedSharePanel).hide();
    }
    switch (target) {
        case "email": $("#shareTabEmail").click(); break;
        case "web": $("#shareTabWeb").click(); break;
        case "response": currentSelectedSharePanel = $("#shareResponseContainer"); currentSelectedSharePanel.show(); selectButton(); break;
    }
} 

function switchSharePanelFromObject(target) {
    if (currentSelectedSharePanel != undefined) {
        $(currentSelectedSharePanel).hide();
    }
    //$.fn.log(target.attr("title"));
    switch (target.attr("title")) {
        case "shareTabEmail": currentSelectedSharePanel = $("#shareEmailContainer"); break;
        case "shareTabWeb": currentSelectedSharePanel = $("#shareWebContainer"); break;
        default: currentSelectedSharePanel = $("#shareResponseContainer"); selectButton(); break;
    }
    //$.fn.log(currentSelectedSharePanel);
    currentSelectedSharePanel.show();
}

function addAction(target) {
    var targetObj = $("#" + target);
    targetObj.attr("title", target);
    targetObj.click(function() { selectButton(targetObj) });
    targetObj.mouseenter(function() { buttonOver(targetObj) });
    targetObj.mouseleave(function() { buttonOut(targetObj) });
    //alert(target);
}

function selectButton(target) {
    if (currentSelectedShareButton != undefined) {
        $(currentSelectedShareButton).removeClass('selected');
        $(currentSelectedShareButton).removeClass('entre');
    }
    currentSelectedShareButton = target;
    if (target) {
        //no target means turn off all buttons
        $(target).addClass('selected');
        switchSharePanelFromObject(target);
    }
}

function buttonOver(target) {
    if (target.hasClass("selected")) {
        return;
    }
    $(target).addClass('entre');
}
function buttonOut(target) {
    if (target.hasClass("selected")) {
        return;
    }
    $(target).removeClass('entre');
}

$(document).ready(
        function() {
            addAction("shareTabEmail");
            addAction("shareTabWeb");
            selectButton($("#shareTabEmail"));
            currentSelectedSharePanel = $("#shareEmailContainer");
        }
);


