﻿//========= general init scripts and variables like stylesheets etc.
var snhost = document.location.protocol + '//' + document.location.host;
var snImagesLoc = snhost + '/tmSubscribe.net/Images/';

(function () {
    var l = document.createElement('link'); // stylesheet
    l.href = snhost + "/tmsubscribe.net/style/sn.css";
    l.type = 'text/css';
    l.rel = 'stylesheet';
    document.getElementById('fb-root').appendChild(l);

    if (document.getElementById('divtopbar') != null)
        document.body.insertBefore(document.getElementById('divtopbar'), document.body.children[0]);
} ());

//========= facebook like init scripts
fbScript = function () {
    window.fbAsyncInit = function () {
        FB.init({ status: true, cookie: true, xfbml: true
        });
        FB.Event.subscribe("edge.create", function (href, widget) {
            // Code to track this click
        });
    };
    var e = document.createElement('script');
    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
    e.async = true;
    document.getElementById('fb-root').appendChild(e);
};

//========= google +1 init scripts
g1Script = function () {
    var g = document.createElement('script');
    g.src = 'https://apis.google.com/js/plusone.js'; //g.async = true;
    document.getElementById('fb-root').appendChild(g);
};

//========= Script to render the Hover element if page came through a FBLike, G1 etc click
RenderHoverDiv = function () {
    var hover = jQuery('.fg-hover');
    for (i = 0; i < hover.length; i++) {
        hover[i].innerHTML = "<div class='fg-hover-alert'><a href='#' id='dummyfocus'></a>"
            + "<div class='fg-pointr'></div><div class='fg-mainmsg'>Please click the "
            + hover[i].getAttribute('verb') + " button to confirm that you " + hover[i].getAttribute('verb')
            + " this article.</div></div>";
    }
    setTimeout(function () {
        jQuery('#dummyfocus').blur(function () { hover.fadeOut(); });
        jQuery('#dummyfocus').focus();
        //jQuery('#dummyfocus').click(function (event) { event.preventDefault(); hover.fadeOut(); });
    }, 2000);
};

//========= Render the Subscribe now button and functionality
RenderSubscribeNow = function () {
    var subscribes = jQuery('.fg-subscribe');
    if (subscribes.length > 0) {
        //========= ajax calls for 'subscribe now' ===================================================================
        var genrlmsg = 'An unexpected error occurred while subscribing you. Please try again later or <a href="mailto:urgent_support@tailoredmail.com">inform us</a>.';
        function postEmailSubscribe() {
            // validations
            if (typeof (hostId) == 'undefined' || typeof (databaseId) == 'undefined') {
                DisplayMessage('', 'Red');
                return false;
            }
            var email = document.getElementById("snemail").value;
            if (email == '' || email.match(/\s+/ig) != null) {
                DisplayMessage('Email address required', 'red');
                return false;
            }
            // post logic
            HideMessage();
	        DisplayWaiting();
	        var posturl = snhost + '/tmwebservice/webservice.asp?accesskey=W45T3RX347EET&action=userAdd&hostid=' // is this safe ?? Need review
                + hostId + '&newsletterid=' + databaseId + '&email=' + email;
            jQuery.post(posturl, function (data) {DisplaySuccess(data);});
        }

        function DisplayMessage(msg, fontcolor) {
            var element = document.getElementById('lblMsg');
            element.style.display = 'block';
            element.style.color = fontcolor;
            if (msg == '') msg = genrlmsg;
            element.innerHTML = msg;
        }

        function HideMessage() {
            document.getElementById('imgValidation').style.display = 'none';
            document.getElementById('lblMsg').style.display = 'none';
        }

        function DisplaySuccess(msg) {
            if(msg.toString().indexOf('saved',0) > 0) {
                document.getElementById('imgValidation').style.display = 'inline';
                document.getElementById('imgValidation').src = 'http://www.tailorednews.com/TailoredMailPublication/Images/checkmark.gif';
            }
            else {
                DisplayMessage(msg, 'red');
                document.getElementById('imgValidation').style.display = 'none';
            }
        }

        function DisplayWaiting() {
            document.getElementById('imgValidation').style.display = 'inline';
            document.getElementById('imgValidation').src = snImagesLoc + 'ajax-loader-snake.gif';
        }
        //========= ajax calls : end ===================================================================

        var parttxt = subscribes.html();
        var subscribeNow = "<a id='subscribenow'>Subscribe Now</a>"
            + "<div class='fg-subscribe-form'>" + parttxt
            + "  <input type='text' id='snemail' name='snemail' />"
            + "  <div style='margin-top:5px;'><input type='image' id='fgsubcsubmit' name='fgsubcsubmit' src='" + snImagesLoc + "sn_accept.png' title='Subscibe Now' />"
            + "  <input type='image' src='" + snImagesLoc + "sn_cancel.png' onclick='jQuery(\".fg-subscribe-form\").fadeOut(); subscdiv = false;' title='Close' />"
            + "  <img id='imgValidation' style='display:none;' /></div>"
            + "  <div id='lblMsg' style='display:none'></div>"
            + "</div>";
        subscribes[0].innerHTML = subscribeNow;
    }
    jQuery('#subscribenow').click(function () {
        if (subscdiv)
        { jQuery('.fg-subscribe-form').fadeOut(); subscdiv = false; }
        else
        { jQuery('.fg-subscribe-form').fadeIn(); subscdiv = true; }
    });
    jQuery('#fgsubcsubmit').click(function () { postEmailSubscribe(); });
};
var subscdiv = false;

ShowTopbar = function () {
    setTimeout(function () {
        jQuery('.fg-shr-bar').fadeIn();
    }, 1000);
}

SNReady = function () {
    jQuery(document).ready(function () {
        RenderSubscribeNow();
        RenderHoverDiv();
        g1Script();
        setTimeout(fbScript, 200);
        ShowTopbar();
    });
}

// Only do anything if jQuery isn't defined
if (typeof jQuery == 'undefined') {
    if (typeof $ == 'function') {
        // warning, global var
        thisPageUsingOtherJSLibrary = true;
    }
    function getScript(url, success) {
        var script     = document.createElement('script');
        script.src = url;

        var head = document.getElementsByTagName('head')[0],
        done = false;

        // Attach handlers for all browsers
        script.onload = script.onreadystatechange = function() {
            if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
                done = true;
                // callback function provided as param
                success();
                script.onload = script.onreadystatechange = null;
            };
        };
        head.appendChild(script);
    };

    getScript(snhost + '/tmSubscribe.net/Include/jquery-1.4.2.js', function() {
        if (typeof jQuery=='undefined') {
            // Super failsafe - still somehow failed...
            alert('Some scripts required to run on this page could not be loaded. Please try again later or contact system administrator to report this.');
        } else {
            // jQuery loaded! Make sure to use .noConflict just in case
            //if (thisPageUsingOtherJSLibrary); else;
            $.noConflict();
            SNReady();
        }
    });

} else { // jQuery was already loaded
    SNReady();
};


