﻿/*
* 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;
//Swap to the different states of the share popup
function swapShareScreens(target) 
{
    if (shareCurrentTarget) 
    {
        turnOffShareScreen(shareCurrentTarget);
    }
    turnOnShareScreen(target);
    shareCurrentTarget = target;

}

//Turn off a specific share screen
function turnOffShareScreen(target) 
{
    var emailTab = document.getElementById("share.tab.email");
    var webTab = document.getElementById("share.tab.web");

    var targetItem;
    switch (target) 
    {
        case "email": targetItem = $("#shareEmailContainer")[0]; targetItem.style.display = "none"; emailTab.style.fontWeight = "normal"; break;
        case "web": targetItem = $("#shareWebContainer")[0]; targetItem.style.display = "none"; webTab.style.fontWeight = "normal"; break;
        case "embed": targetItem = $("#shareEmbedContainer")[0]; targetItem.style.display = "none"; break;
        case "response": targetItem = $("#shareResponseContainer")[0]; targetItem.style.display = "none"; break;
    }
    
    //Bypass for email only
    targetItem =$("#shareEmailContainer")[0]; targetItem.style.display = "none"; 
}
//Turn on a specific share screen
function turnOnShareScreen(target) 
{
    
    var emailTab = document.getElementById("share.tab.email");
    var webTab = document.getElementById("share.tab.web");

    var targetItem;
    switch (target) {
        case "email": targetItem = $("#shareEmailContainer")[0]; targetItem.style.display = "inline"; emailTab.style.fontWeight = "bold"; break;
        case "web": targetItem = $("#shareWebContainer")[0]; targetItem.style.display = "inline"; webTab.style.fontWeight = "bold"; break;
        case "embed": targetItem = $("#shareEmbedContainer")[0]; targetItem.style.display = "inline"; break;
        case "response": targetItem = $("#shareResponseContainer")[0]; targetItem.style.display = "inline"; break;
    }
    
    //Bypass for email only
    targetItem = $("#shareEmailContainer")[0]; targetItem.style.display = "inline"; 
}

//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].disabled = true;
        $("#sendButton")[0].disabled = true;
        $("#verifyField")[0].disabled = false;

        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();
        var _article = $("#articleField").val();
    

        $.post("utils/shareHandler.ashx", { fromName: _fromName, fromEmail: _fromEmail, toName: _toName, toEmail: _toEmail, personalMessage: _personalMessage, vid: _vid, preview: _preview, shareUrl:_shareUrl, article: _article }, shareFormSubmitCallback);
        $("#shareResponseContent").html('<img src="images/loading_animation.gif" />');
        //showResponse();
    }
    //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><h4>There was a problem sending your message.</h4></p><p><br/>Please try again later.</p>");
        } 
        else if (responseText == "2") 
        {
            //Invalid session
            $("#shareResponseContent").html("<p><h3>Oops!</h3></p><p><br/>Please check the verification number.</p>");
            //Update the verification image
            resetVerification();
        } 
        else 
        {
            //Success
            $("#shareResponseContent").html("<p><h3>Thank you.</h3></p><p><br/>Your message has been sent.</p>");
            resetForm();
        }
        //swapShareScreens("response");
        showResponse();
        
    } 
    else 
    {
        //Show the preview form
        $('#sharePreviewContent').html(responseText);
            $('#sharePreviewModal').modal(
                    {
                        closeClass: "modalClose",
                        position: ['106px', ]
                    }
                );
    }
    
    //alert( "message: " + responseText );
}


function showResponse() 
{
    $("#shareResponseContainer").show();
    $("#shareEmailContainer").hide();
}
function hideResponse() 
{
    $("#shareResponseContainer").hide();
    $("#shareEmailContainer").show();
}

/**  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 = "utils/verificationimage.ashx?file=" + Math.random() * 10000;
    $("#verifyField")[0].value = "";
    $("#verificationLabel")[0].innerHTML = "Enter the number you see below*";
    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("utils/checkVerification.ashx", { number: target.value }, checkVerifyImageCallback);
    }
}
//Callback handler for verification request.
function checkVerifyImageCallback(results) 
{
    if (results == "1") 
    {
        setFieldToInvalid($("#verifyField")[0]);
        $("#verificationLabel")[0].innerHTML = "Oops! Please try again.";
        resetVerification();
        isVerified = false;
    } 
    else if (results == "2") 
    {
        setFieldToInvalid($("#verifyField")[0]);
        resetVerification();
    } 
    else 
    {
        setFieldToValid($("#verifyField")[0]);
        $("#verificationLabel")[0].innerHTML = "Verification Complete!";
        isVerified = true;
    }
}
//Hide the share this container
function hideShareThis() 
{
    //$("#shareContainer")[0].style.display = "none";
    $("#shareContainer").fadeOut(500);
    hideResponse();
}
//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();
    $("#shareContainer").fadeIn(500);
    //$("#shareContainer")[0].style.display = "block";
    $("#shareUrlField")[0].value = pageUrl;
    $("#sharePageTitleField")[0].value = pageTitle;
    $("#copyURLField")[0].value = 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(); });
});


