﻿$.ajaxSetup({
    type: 'post',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json'
});

$(document).ready(function () {
    social.init();
});

var social =
{
    socialControls: [],
    page: null,
    imgPath: 'Images/icons/social/',
    qs: null,
    articleID: 0,
    sites: null,
    bmURL: null,
    bmWho: null,
    emailSiteID: null,
    printOverride: null,
    pdfOverride: null,
    pdfHide: false,
    shortURL: null,
    isShort: false,
    currentSocialSite: null,


    addSocialControlID: function (cid) {
        social.socialControls[social.socialControls.length] = cid;
        var test = test;
    },

    init: function () {
        social.registerControls();
        social.parseURL();
        social.getShareSites();
        social.adjustLocations();
        social.setEvents();
        social.loadEmailPanels();
        social.isShort = false;
    },

    registerControls: function () {
        social.socialControls = new Array();
        var sscCons = $('.sscSocialContainerParent');
        for(c = 0; c < sscCons.length; c += 1) {
            var scid = $(sscCons[c]).attr('id');
            social.socialControls[social.socialControls.length] = scid.slice(0, scid.indexOf('_sscSocialContainer'));
        }
    },

    parseURL: function () {
        var uPath = window.document.location.href;

        if(uPath.indexOf('?') > 0) {
            social.qs = uPath.substring(uPath.indexOf('?'));
        }
        else {
            social.qs = '';
        }

        uPath = uPath.substring(uPath.lastIndexOf('/', (uPath.length - 1)) + 1);
        var qryIX = uPath.indexOf('?');
        if(qryIX > 0) {
            social.page = uPath.substring(0, qryIX);
        }
        else {
            social.page = uPath;
        }
    },

    adjustLocations: function () {
        for(c = 0; c < social.socialControls.length; c += 1) {
            var offset = $('#' + social.socialControls[c] + '_sscSocialContainer').offset();
            $('#' + social.socialControls[c] + '_sscSocialFlyout').css('top', (offset.top + 28) + 'px').css('left', (offset.left - 192) + 'px');
            $('.emailPanelRoomy').css('left', (offset.left - 297) + 'px');
        }
    },

    setEvents: function () {
        for(c = 0; c < social.socialControls.length; c += 1) {
            $('#' + social.socialControls[c] + '_sscMoreStart').click(function () {
                var idPart = social.parseEventID(this);
                if($('#' + idPart + '_sscEmailPanel').css('display') == 'none') {
                    $('#' + idPart + '_sscSocialShare').addClass('socialTextOn');
                    $('#' + idPart + '_sscSocialFlyout').show('slow');
                }
            }); //.mouseleave(function () {
            //    var idPart = social.parseEventID(this);
            //    $('#' + idPart + '_sscSocialShare').removeClass('socialTextOn');
            //    if (social.page != 'ShareThis.aspx') {
            //       $('#sscSocialFlyout').hide('slow');
            //  }
            //});

            $('#' + social.socialControls[c] + '_sscSocialFlyoutClose').click(function () {
                var idPart = social.parseEventID(this);
                $('#' + idPart + '_sscSocialFlyout').hide('slow');
            });
        }
    },

    loadEmailPanels: function () {
        for(c = 0; c < social.socialControls.length; c += 1) {
            emailPanel.loadPanel(social.socialControls[c] + '_sscEmailPanel', social.socialControls[c] + '_sscEmailConfirmation');
        }
    },

    parseEventID: function (ele) {
        var splitID = ele.id.split('_');
        var idPart = '';
        var delim = '';
        for(i = 0; i < splitID.length - 1; i += 1) {
            idPart += delim + splitID[i];
            delim = '_';
        }
        return idPart;
    },

    getShareSites: function () {
        $.ajax({
            type: 'post',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            url: 'SocialSharingHandler.aspx/GetActiveList',
            data: '{referringPage:"' + social.page + '",queryString:"' + social.qs + '"}',
            success: function (data) {
                social.sites = data.d.Sites;
                social.bmURL = data.d.URL;
                social.bmWho = data.d.Title;
                social.articleID = data.d.ArticleID;
                social.hideSites();
                social.loadFeatureSet();
                social.loadSharingMenu();
            },
            error: function (err) {
                $('[id$=_sscSocialContainer]').hide();
            }
        });
    },

    bitifyLink: function (url) {
        social.shortURL = url;
        BitlyClient.shorten(url, 'social.bitCB');
    },

    bitCB: function (data) {
        var surl = social.bmURL;
        if(data.errorCode === 0) {
            var result;
            for(var r in data.results) {
                result = data.results[r];
                result['longUrl'] = r;
                break;
            }
            surl = result['shortUrl'];
        }
        social.shortURL = surl;
        social.isShort = true;
        social.openSite();
    },

    hideSites: function () {
        if(social.pdfHide === true) {
            var at = -1;
            for(s = 0; s < social.sites.length; s += 1) {
                if(social.sites[s].Name == 'Create PDF') {
                    at = s;
                }
            }
            if(at >= 0) social.sites.splice(at, 1);
        }
    },

    loadFeatureSet: function () {
        for(i = 0; i < social.sites.length; i = i + 1) {
            if(social.sites[i].IsFeatured === true) {
                var ipth = social.imgPath + social.sites[i].Icon;
                for(c = 0; c < social.socialControls.length; c += 1) {
                    $('#' + social.socialControls[c] + '_sscSocialFeatureSet').append('<span><img src="' + ipth + '" alt="' + social.sites[i].Name + '" title="' + social.sites[i].Name + '" /></span>');
                    $('#' + social.socialControls[c] + '_sscSocialFeatureSet > span > img[alt="' + social.sites[i].Name + '"]').attr('targetID', social.socialControls[c]);
                    if(social.sites[i].Name == 'Print' && social.printOverride != null) {
                        $('#' + social.socialControls[c] + '_sscSocialFeatureSet > span > img[alt="' + social.sites[i].Name + '"]').click(social.printOverride);
                    }
                    else {
                        $('#' + social.socialControls[c] + '_sscSocialFeatureSet > span > img[alt="' + social.sites[i].Name + '"]').click(function () {
                            social.siteClicked(this);
                        });
                    }
                }
            }
        }
        for(c = 0; c < social.socialControls.length; c += 1) {
            $('#' + social.socialControls[c] + '_sscSocialFeatureSet img').addClass('img24x24');
            $('#' + social.socialControls[c] + '_sscSocialFeatureSet span').addClass('featurePadding');
        }
    },

    loadSharingMenu: function () {
        for(i = 0; i < social.sites.length; i = i + 1) {

            var ipth = social.imgPath + social.sites[i].Icon;
            var ihtml = '<div><img src="' + ipth + '" alt="' + social.sites[i].Name + '" /><span> ' + social.sites[i].Name + '</span></div>';
            var m = i % 2;
            for(c = 0; c < social.socialControls.length; c += 1) {
                if(m === 0) {
                    $('#' + social.socialControls[c] + '_sscSocialEntryLeft').append(ihtml);
                }
                else {
                    $('#' + social.socialControls[c] + '_sscSocialEntryRight').append(ihtml);
                }
                $('#' + social.socialControls[c] + '_sscSocialFlyoutEntries > div > div > img[alt="' + social.sites[i].Name + '"]').parent('div').attr('targetID', social.socialControls[c]);
                $('#' + social.socialControls[c] + '_sscSocialFlyoutEntries > div > div > img[alt="' + social.sites[i].Name + '"]').parent('div').attr('alt', social.sites[i].Name);
                if(social.sites[i].Name == 'Print' && social.printOverride != null) {
                    $('#' + social.socialControls[c] + '_sscSocialFlyoutEntries > div > div > img[alt="' + social.sites[i].Name + '"]').click(social.printOverride);
                }
                else {
                    $('#' + social.socialControls[c] + '_sscSocialFlyoutEntries > div > div > img[alt="' + social.sites[i].Name + '"]').parent('div').click(function () {
                        social.siteClicked(this);
                    });
                }
            }
        }
        for(c = 0; c < social.socialControls.length; c += 1) {
            $('#' + social.socialControls[c] + '_sscSocialFlyoutEntries img').addClass('img24x24');
            $('#' + social.socialControls[c] + '_sscSocialFlyoutEntries div').addClass('socialEntry');
            $('#' + social.socialControls[c] + '_sscSocialFlyoutEntries span').addClass('socialEntryText');
            $('#' + social.socialControls[c] + '_sscSocialFlyoutEntries > div > div').css('cursor', 'pointer');
        }

        if(social.page.toLowerCase() == 'sharethis.aspx') {
            $('#' + social.socialControls[0] + '_sscSocialFlyout').show('slow');
        }
    },

    siteClicked: function (ele) {
        var alt = $(ele).attr('alt');
        for(i = 0; i < social.sites.length; i = i + 1) {
            if(social.sites[i].Name == alt) {
                if(social.sites[i].ShareURL != '') {
                    social.currentSocialSite = social.sites[i].BaseURL;
                    social.trackSocialSite(social.sites[i]);

                    if(social.isShort === true) {
                        social.openSite();
                    }
                    else {
                        social.bitifyLink(social.bmURL);
                    }

                }
                else if(social.sites[i].Name == 'Email Friend') {
                    social.emailSiteID = social.sites[i].SiteID;
                    social.emailClicked(ele);
                }
                else if(social.sites[i].Name == 'Bookmark') {
                    social.bookmarkClicked();
                    social.trackSocialSite(social.sites[i]);
                }
                else if(social.sites[i].Name == 'Print') {
                    window.print();
                    social.trackSocialSite(social.sites[i]);
                }
                else if(social.sites[i].Name == 'Create PDF') {
                    pdfPrinter.print();
                    social.trackSocialSite(social.sites[i]);
                }
                break;
            }
        }
    },

    openSite: function () {
        var ssite = social.currentSocialSite.replace('{url}', encodeURIComponent(social.shortURL));
        ssite = ssite.replace('{title}', encodeURIComponent(social.bmWho));
        window.open(ssite, '_blank', '', false);
    },

    emailClicked: function (ele) {
        var idPart = $(ele).attr('targetID');
        if($('#' + idPart + '_sscEmailPanel').css('display') == 'none') {
            $('#' + idPart + '_sscSocialFlyout').hide('slow');
            emailPanel.showPanel(social.articleID, social.bmURL, idPart + '_sscEmailPanel');
        }
        else {
            emailPanel.cancelEmail(idPart + '_sscEmailPanel');
            if(social.page == 'ShareThis.aspx') {
                $('#' + idPart + '_sscSocialFlyout').show('slow');
            }
        }
    },

    bookmarkClicked: function () {
        if(document.all) {
            window.external.AddFavorite(social.bmURL, social.bmWho);
        }
        else if(window.sidebar) {
            window.sidebar.addPanel(social.bmWho, social.bmURL, 'false');
        }
        else {
            alert('Press <Control> + D to add bookmark');
        }
    },

    trackSocialSite: function (ssite) {
        $.ajax({
            url: 'SocialSharingTrackingHandler.aspx/TrackSocialSite',
            data: '{siteID:"' + ssite.SiteID + '",url:"' + social.bmURL + '",title:"' + social.bmWho + '"}',
            success: function (data) { },
            error: function (error) { }
        });
    },

    // Called from the email panel
    trackSocialEmail: function (fromEmail) {
        $.ajax({
            url: 'SocialSharingTrackingHandler.aspx/TrackSocialEmail',
            data: '{siteID:"' + social.emailSiteID + '",url:"' + social.bmURL + '",title:"' + social.bmWho + '", fromEmail:"' + fromEmail + '"}',
            success: function (data) { },
            error: function (error) { }
        });
    }
};

var pdfPrinter =
{
    articleID: 0,
    targetURL: '',

    print: function () {

        var qstring = '';

        if (social.articleID != null) {
            var res = social.bmURL.search(/articleid=/i);
            if (res > 0) {qstring = '?targetURL=' + social.bmURL; }
            else { qstring = '?targetURL=' + social.bmURL + '&articleID=' + social.articleID; }
        }
        else {
            qstring = '?targetURL=' + social.bmURL + '&articleID=0';
        }

        window.open('PDFCreator.aspx' + qstring, '_blank', '', false);

    }
}
