﻿var editPageFilePath = '/utility/editpage.aspx';
var inTelligentEditMode = false;

if (window.location.pathname.toLowerCase() == editPageFilePath)
    inTelligentEditMode = true;

function encodeURL(text) {
    text = text.replace(/_/g, "_5F00_"); //underscore
    text = text.replace(/-/g, "_2D00_"); //minus
    text = text.replace(/\+/g, "_2B00_"); //plus
    text = text.replace(/@/g, "_4000_"); //@
    text = text.replace(/!/g, "_2100_"); //!
    text = text.replace(/ /g, "-"); //space

    return text;
}

function decodeURL(text) {
    text = text.replace("-", " "); //space
    text = text.replace("_5F00_", "_"); //underscore
    text = text.replace("_2D00_", "-"); //minus
    text = text.replace("_2B00_", "+"); //plus
    text = text.replace("_4000_", "@"); //@
    text = text.replace("_2100_", "!"); //!  
    return text;
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

function deleteCookie(c_name) {
    document.cookie = c_name + "=; path=/";
}

function AssignOverlayToLink(linkId, containerId) {
    $("#" + linkId).attr("href", "javascript:void(0);")
                .unbind("click").click(function () {
                    tb_show("", "#TB_inline?width=800&height=500&inlineId=" + containerId, null);
                });
}

function postwith(to, params) {
    var myForm = document.createElement("form");
    myForm.method = "post";
    myForm.action = to;
    for (var k in params) {
        var myInput = document.createElement("input");
        myInput.setAttribute("name", k);
        myInput.setAttribute("value", params[k]);
        myForm.appendChild(myInput);
    }
    document.body.appendChild(myForm);
    myForm.submit();
    document.body.removeChild(myForm);
    return false;
}

function getUName() {
    var usrCookie = getCookie("svsusername");
    var cookieItems = null;
    if (usrCookie) {
        cookieItems = usrCookie.split(',');

        if (cookieItems.length > 1) {
            return cookieItems[1];
        }
    }
    return '';
}

function getUTeam() {
    var usrCookie = getCookie("svsusername");
    var cookieItems = null;
    if (usrCookie) {
        cookieItems = usrCookie.split(',');

        if (cookieItems.length >= 4) {
            return cookieItems[3];
        }
    }
    return '';
}

function getUAvatar() {
    var usrCookie = getCookie("svsusername");
    var cookieItems = null;
    if (usrCookie) {
        cookieItems = usrCookie.split(',');

        if (cookieItems.length >= 4) {
            return cookieItems[2];
        }
    }
    return '';
}

function getUDisplayName() {
    var usrCookie = getCookie("svsusername");
    var cookieItems = null;
    if (usrCookie) {
        cookieItems = usrCookie.split(',');

        if (cookieItems.length >= 4) {
            return cookieItems[0];
        }
    }
    return '';
}


var Browser = {
    Version: function () {
        var version = 999; // we assume a sane browser
        if (navigator.appVersion.indexOf("MSIE") != -1)
        // bah, IE again, lets downgrade version number
            version = parseFloat(navigator.appVersion.split("MSIE")[1]);
        return version;
    }
}


//added the on click event for the facebook share link on news/blogs
$('#facebookShare').live('click', function (e) {
    e.preventDefault();
    var sPath = window.location.pathname;
    var sPage = sPath.substring(sPath.lastIndexOf('/') + 1).replace('.aspx','').replace(/-/g, ' ');
    facebookPublish(document.URL, sPage, 'Spots v Stripes', '') 
});

var qsParm = new Array();
function qs() {
    var query = window.location.search.substring(1);
    var parms = query.split('&');
    for (var i = 0; i < parms.length; i++) {
        var pos = parms[i].indexOf('=');

        if (pos > 0) {
            var key = parms[i].substring(0, pos);
            var val = parms[i].substring(pos + 1);
            qsParm[key] = val;
        }
    }
}

function getQuerystringValue(parameter) {
    var querystring = window.location.search.substring(1);
    var parameters = querystring.split("&");
    for (var i = 0; i < parameters.length; i++) {
        var pair = parameters[i].split("=");
        if (pair[0] == parameter) {
            return pair[1];
        }
    }
}

function setCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : "; expires=" + exdate.toUTCString()) + "; path=/";
}

function updateAccessedDate() {
    // DEPRECATED COMMENT
    // added the following line today: 15.12.2010 not to have the feature included in today's build
    // remove this line to have the functionality
    // END OF DEPRECATED COMMENT
    // Dani Horon : 21.01.2011
    // I commented this return to enable the last accessed date functionality, asked by Danny Russell and Erden Impraimoglou
    //return;
    var uName = getUName();
    // verify if we are in the logged in state
    if (uName != '') {
        var lastUpdateCookieVal = getCookie("updAccessedDate" + uName);
        var d = new Date();
        // verify if we need to update the server
        if (lastUpdateCookieVal == '' ||
        lastUpdateCookieVal != d.toDateString()) {

            // set the cookie
            setCookie('updAccessedDate' + uName, lastUpdateCookieVal = d.toDateString(), 1);
            // set the date on server
            $.ajax({
                url: "/proxy.aspx",
                data: "command=updateLastSiteAccessedDate&u=" + uName
            });
        }
    }
}

function drawGraph(values, uniqueID) {

    $(document).ready(function () {
        $(".test-case" + uniqueID).show(1000);
        commonTestData = []
        var total = 0;
        var mySplitResult = values.split('*');
        for (i = 0; i < mySplitResult.length; i++) {
            var questionName = mySplitResult[i].split(';')[0];
            var value = parseInt(mySplitResult[i].split(';')[1]);
            total += value;
            commonTestData.push([value, { label: questionName}]);
        }

        $('#dynamic-properties-graph' + uniqueID).tufteBar({
            data: commonTestData,
            barLabel: function (i) { return this[0] },
            axisLabel: function (i) { return this[1].label }
        });
        showPercent(total);
    });
}

function drawPieGraph(values, uniqueID) {
    $(document).ready(function () {
        Raphael.fn.pieChart = function (cx, cy, r, values, labels, stroke) {
            var paper = this,
        rad = Math.PI / 180,
        chart = this.set();
            function sector(cx, cy, r, startAngle, endAngle, params) {
                var x1 = cx + r * Math.cos(-startAngle * rad),
            x2 = cx + r * Math.cos(-endAngle * rad),
            y1 = cy + r * Math.sin(-startAngle * rad),
            y2 = cy + r * Math.sin(-endAngle * rad);
                return paper.path(["M", cx, cy, "L", x1, y1, "A", r, r, 0, +(endAngle - startAngle > 180), 0, x2, y2, "z"]).attr(params);
            }
            var angle = 0,
        total = 0,
        start = 0,
        process = function (j) {
            var value = values[j],
                angleplus = 360 * value / total,
                popangle = angle + (angleplus / 2),
                color = "hsb(" + start + ", 1, .5)",
                ms = 500,
                delta = 30,
                bcolor = "hsb(" + start + ", 1, 1)",
                p = sector(cx, cy, r, angle, angle + angleplus, { gradient: "90-" + bcolor + "-" + color, stroke: stroke, "stroke-width": 3 }),
                txt = paper.text(cx + (r + delta + 55) * Math.cos(-popangle * rad), cy + (r + delta + 1) * Math.sin(-popangle * rad), labels[j]).attr({ fill: bcolor, stroke: "none", opacity: 0, "font-family": 'Fontin-Sans, Arial', "font-size": "12px" });
            p.mouseover(function () {
                p.animate({ scale: [1.1, 1.1, cx, cy] }, ms, "elastic");
                txt.animate({ opacity: 1 }, ms, "elastic");
            }).mouseout(function () {
                p.animate({ scale: [1, 1, cx, cy] }, ms, "elastic");
                txt.animate({ opacity: 0 }, ms);
            });
            angle += angleplus;
            chart.push(p);
            chart.push(txt);
            start += .1;
        };
            for (var i = 0, ii = values.length; i < ii; i++) {
                total += values[i];
            }
            for (var i = 0; i < ii; i++) {
                process(i);
            }
            return chart;
        };

        (function (raphael) {
            $(function () {
                var values1 = [];
                labels = [];
                var mySplitResult = values.split('*');
                for (i = 0; i < mySplitResult.length; i++) {
                    var questionName = mySplitResult[i].split(';')[0];
                    var value = parseInt(mySplitResult[i].split(';')[1]);
                    values1.push(value);
                    labels.push(questionName);
                }

                $(".test-case" + uniqueID).show(1000);
                raphael("dynamic-properties-graph" + uniqueID, 200, 200).pieChart(100, 100, 50, values1, labels, "#fff");
            });
        })(Raphael.ninja());
    });
}



function GetPollResults(serviceURL,method,pollName,uniqueID, displayMode) {

    var res = serviceURL + method + pollName;
    $.ajax({
        async: "false",
        url: res,
        dataType: "jsonp",
        success: function (data) {
            $('#pollResults' + uniqueID)[0].value = data;
            if (displayMode == 'Graph') {
                drawGraph($('#pollResults'+uniqueID)[0].value, uniqueID);
            }
            else {
                drawPieGraph($('#pollResults'+uniqueID)[0].value, uniqueID);
            }
        }
    });
}

function getQueryVariable(variable) {
    variable = variable.toLowerCase();
    var query = window.location.search.substring(1).toLowerCase();
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }
}

