﻿var regEmpty = new RegExp(/^\s+$/);
var regInject = new RegExp(/.*(<script|style=|<link)+.*/im); // ^([\\w|\\s]*(<script{1})[\\w|\\s]*)$
var regNewLine = new RegExp(/\n/g);
var regNewLineHTML = new RegExp("<br />", "ig");
var regTab = new RegExp(/\t/g);
var regTabHTML = new RegExp("<b class=\"imitTab\">&nbsp;</b>", "ig");

$.address.strict(false);
$.address.query = new Object({
    np: function() { return extractHashStringValue($.address.value(), "np"); },
    nid: function() { return extractHashStringValue($.address.value(), "nid"); },
    lid: function() { return extractHashStringValue($.address.value(), "lid"); },
    tid: function() { return extractHashStringValue($.address.value(), "tid"); },
    sid: function() { return extractHashStringValue($.address.value(), "sid"); },
    gid: function() { return extractHashStringValue($.address.value(), "gid"); },
    pid: function() { return extractHashStringValue($.address.value(), "pid"); },
    reload: function() { return extractHashStringValue($.address.value(), "reload"); }
});

String.prototype.unescapeHTML = function() {
    return unescape(this).replace(regNewLineHTML, "\n").replace(regTabHTML, "\t");
};
String.prototype.escapeHTML = function() {
    return escape(this.replace(regNewLine, "<br />").replace(regTab, "<b class=\"imitTab\">&nbsp;</b>"));
};

var mainMenu = {
    SelectItem: function(itemID) {
        if (itemID != null) {
            $(".hdr #" + itemID).addClass("hdrMenuSelected");
        }
    },
    CategoryID: function() {
        return extractQueryStringValue("team");
    }
};

var mainCoverPanel = {
    Initialize: function() {
        $(".mainCoverPanel").css({ "top": "0", "left": "0", "opacity": "0.7" });
        $(window).bind("scroll", mainCoverPanel.PositionPanel);
        $(window).bind("resize", mainCoverPanel.PositionPanel);
    },
    Toggle: function(display) {
        $(".mainCoverPanel").toggleClass("dontDisplay", !display);
        this.PositionPanel();
    },
    PositionPanel: function(force) {
        if (force == null) { force = false; }
        if (!$(".mainCoverPanel").hasClass("dontDisplay") || force == true) {
            $(".mainCoverPanel").height($(document).height())
                                .width($(window).width() + $(window).scrollLeft());
        }
    }
};

var subMenu = {
    SelectedItemID: null,
    SelectItem: function(itemID) {
        if (itemID != null) {
            $(".cnt .tabs #" + itemID).addClass("tabsSelected");
        }
        this.SelectedItemID = itemID;
    }
};

var teamHeader = {
    SetHeaderText: function(text) {
        $(".cnt #teamHeader").html(text);
    },
    SetHeaderByPageID: function(pageID) {
        var obj = callGetCategoryByID(mainMenu.CategoryID());
        var newText = new String();

        switch (pageID.toLowerCase()) {
            case "teamnews":
                newText = "News";
                break;
            case "info":
                newText = "Information";
                break;
            case "results":
                newText = "Results & Statistics";
                break;
            case "gallery":
                newText = "Galleries";
                break;
            default:
                ""
        }
        if (obj != null) {
            this.SetHeaderText(obj.CategoryDescription + " " + newText);
        }
        else {
            this.SetHeaderText(newText);
        }
    }
};


function extractQueryStringValue(queryElementName) {
    var queryString = new Array();
    queryString = window.location.search.slice(1).split("&");
    for (i = 0; i < queryString.length; i++) {
        var elemArray = queryString[i].split("=");
        if (elemArray.length > 1 && elemArray[0].toLowerCase() == queryElementName.toLowerCase() && !isNaN(elemArray[1])) {
            return elemArray[1];
        }
    }
    return null;
};

function extractPathIdentifier(partIdx) {
    var pathname;
    pathname = window.location.pathname.length > 1 ? window.location.pathname.slice(1).split("/") : new Array("default");
    if (pathname != null && pathname.length > partIdx) {
        pathname = pathname[partIdx].split(".");
        if (pathname != null && pathname.length > 0) {
            return pathname[0].toLowerCase() == "team" ? pathname[0] + extractQueryStringValue("team") : pathname[0];
        }
    }

    return null;
}

function extractHashStringValue(hashString, hashElementName) {
    var queryString = new Array();
    queryString = hashString.split(/[\/&#]/);
    for (i = 0; i < queryString.length; i++) {
        var elemArray = queryString[i].split("=");
        if (elemArray.length > 1 && elemArray[0].toLowerCase() == hashElementName.toLowerCase() && !isNaN(elemArray[1])) {
            return elemArray[1];
        }
    }
    return null;
}

function getURL(pathname) {
    return window.location.protocol + "//" + window.location.host + pathname + window.location.search;
}

function parseJSONDateFromUTC(date, formatString) {
    //debugger   
    var d = new Date(parseInt(date.slice(6, 20)));
    //d = new Date(d.getTime() - (d.getTimezoneOffset() * 60000));
    return d.format(formatString);
}

Date.prototype.format = function(formatString) {
    var token = /d{1,4}|M{1,4}|yy(?:yy)?|([HhmsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g
    var months = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
    var monthsLong = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
    var days = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
    var daysLong = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");

    var pad = function(val, len) {
        val = String(val);
        len = len || 2;
        while (val.length < len) val = "0" + val;
        return val;
    }

    var d = this.getDate();
    var D = this.getDay();
    var M = this.getMonth();
    var y = this.getFullYear();
    var H = this.getHours();
    var m = this.getMinutes();
    var s = this.getSeconds();
    var L = this.getMilliseconds();

    var flags = {
        d: d,
        dd: pad(d),
        ddd: days[D],
        dddd: daysLong[D],
        M: M + 1,
        MM: pad(M + 1),
        MMM: months[M],
        MMMM: monthsLong[M],
        yy: String(y).slice(2),
        yyyy: y,
        h: H % 12 || 12,
        hh: pad(H % 12 || 12),
        H: H,
        HH: pad(H),
        m: m,
        mm: pad(m),
        s: s,
        ss: pad(s),
        l: pad(L, 3),
        L: pad(L > 99 ? Math.round(L / 10) : L),
        t: H < 12 ? "a" : "p",
        tt: H < 12 ? "am" : "pm",
        T: H < 12 ? "A" : "P",
        TT: H < 12 ? "AM" : "PM"
    };

    return formatString.replace(token, function($0) {
        return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
    });
}


function callGetCategoryByID(categoryID) {
    var res = null;
    $.ajax({
        async: false,
        cache: false,
        type: "POST",
        url: "/ServiceOther.aspx/GetCategoryByID",
        contentType: "application/json; charset=utf-8",
        data: "{categoryID:" + categoryID + "}",
        dataType: "json",
        success: function(result) {
            if (result != null && result.d != null) {
                res = result.d;
            }
        },
        error: call_error
    });
    return res;
}

function callGetCategoryAll() {
    var res = null;
    $.ajax({
        async: false,
        cache: false,
        type: "POST",
        url: "/ServiceOther.aspx/GetCategoryAll",
        contentType: "application/json; charset=utf-8",
        data: "{}",
        dataType: "json",
        success: function(result) { res = result.d; },
        error: call_error
    });
    return res;
}

/* BEGIN NEWS/COMMENTS */
function callGetNewsByPage(pageNumber, categoryID) {
    var res;
    $.ajax({
        cache: false,
        async: false,
        type: "POST",
        url: "/ServiceNews.aspx/GetNewsByPage",
        contentType: "application/json; charset=utf-8",
        data: "{pageNumber:" + pageNumber + ",categoryID:" + (categoryID != null ? categoryID : "null") + "}",
        dataType: "json",
        success: function(result) { res = result.d; },
        error: call_error
    });
    return res;
}

function callGetNewsByID(newsID, langID) {
    var res;
    $.ajax({
        cache: false,
        async: false,
        type: "POST",
        url: "/ServiceNews.aspx/GetNewsByID",
        contentType: "application/json; charset=utf-8",
        data: "{newsID:" + newsID + ", languageID:" + (langID == null ? "null" : langID) + "}",
        dataType: "json",
        success: function(result) { res = result.d; },
        error: call_error
    });
    return res;
}

function callGetCommentsByNews(newsID) {
    var res;
    $.ajax({
        cache: false,
        async: false,
        type: "POST",
        url: "/ServiceNews.aspx/GetCommentsByNews",
        contentType: "application/json; charset=utf-8",
        data: "{newsID:" + newsID + "}",
        dataType: "json",
        success: function(result) { res = result.d; },
        error: call_error
    });
    return res;
}

function callGetNewsAll() {
    var res;
    $.ajax({
        cache: false,
        async: false,
        type: "POST",
        url: "/ServiceNews.aspx/GetNewsAll",
        contentType: "application/json; charset=utf-8",
        data: "{}",
        dataType: "json",
        success: function(result) { res = result.d; },
        error: call_error
    });
    return res;
}

function callAddComment(newsID, commentText, author, repliedToID) {
    //1. Gather data from fields.
    if (repliedToID == "") { repliedToID = null; }

    //2. Validate data.
    if (newsID == null || newsID == "") {
        bwesaNews.NewCommentErrorMessage(true, " Unable to add comment. Please click 'Cancel' and try again. ");
        return -2;
    }

    if (commentText == null || commentText == "" || regEmpty.test(commentText)) {
        bwesaNews.NewCommentErrorMessage(true, " Comment Text field cannot be empty. ");
        return -2;
    }

    if (author == null || author == "") {
        bwesaNews.NewCommentErrorMessage(true, " Author field cannot be empty. ");
        return -2;
    }

    if (regInject.test(commentText)
        || regInject.test(author)
        || regInject.test(unescape(commentText))
        || regInject.test(unescape(commentText))) {
        bwesaNews.NewCommentErrorMessage(true, " Don't inject anything here. ");
        return -2;
    }

    //3. Send request to server
    var res;
    $.ajax({
        cache: false,
        async: false,
        type: "POST",
        url: "/ServiceNews.aspx/AddComment",
        contentType: "application/json; charset=utf-8",
        data: "{newsID:'" + newsID + "', commentText:'" + commentText + "', author:'" + author + "', repliedToID:" + repliedToID + "}",
        dataType: "json",
        //success: callAddComment_success,
        success: function(result) { res = result.d; },
        error: call_error
    });
    return res;
}

/* END NEWS/COMMENTS */

/* BEGIN EVENTS */
function callGetEvents() {
    var res;
    $.ajax({
        cache: false,
        async: false,
        type: "POST",
        url: "/ServiceEvent.aspx/GetEvents",
        contentType: "application/json; charset=utf-8",
        data: "{}",
        dataType: "json",
        success: function(result) { res = result.d; },
        error: call_error
    });
    return res;
}
/* END EVENTS */

/* BEGIN POLL */
function callAddPollVote(pollID, pollItemID) {
    var res;
    $.ajax({
        cache: false,
        async: false,
        type: "POST",
        url: "/ServiceNews.aspx/AddPollVote",
        contentType: "application/json; charset=utf-8",
        data: "{pollID:'" + pollID + "', pollItemID:" + pollItemID + "}",
        dataType: "json",
        success: function(result) { res = result; },
        error: call_error
    });
    return res;
}

function callGetPollList() {
    var res;
    $.ajax({
        cache: false,
        async: false,
        type: "POST",
        url: "/ServiceNews.aspx/GetPollList",
        contentType: "application/json; charset=utf-8",
        data: "{}",
        dataType: "json",
        success: function(result) { res = result.d; },
        error: call_error
    });
    return res;
}

/* END POLL */

/* BEGIN STATISCTICS */
function callGetSeasonsByTeam(teamID) {
    var res;
    $.ajax({
        cache: false,
        async: false,
        type: "POST",
        url: "/ServiceStats.aspx/GetSeasonsByTeam",
        contentType: "application/json; charset=utf-8",
        data: "{teamID:" + teamID + "}",
        dataType: "json",
        success: function(result) { res = result.d; },
        error: call_error
    });
    return res;
}

function callGetGamesBySeason(seasonID) {
    var res;
    $.ajax({
        cache: false,
        async: false,
        type: "POST",
        url: "/ServiceStats.aspx/GetGamesBySeason",
        contentType: "application/json; charset=utf-8",
        data: "{seasonID:" + seasonID + "}",
        dataType: "json",
        success: function(result) { res = result.d; },
        error: call_error
    });
    return res;
}

function callGetSeasonSummary(seasonID) {
    var res;
    $.ajax({
        cache: false,
        async: false,
        type: "POST",
        url: "/ServiceStats.aspx/GetSeasonSummary",
        contentType: "application/json; charset=utf-8",
        data: "{seasonID:" + seasonID + "}",
        dataType: "json",
        success: function(result) { res = result.d; },
        error: call_error
    });
    return res;
}

function callGetGameDetails(seasonID, gameID) {
    var res;
    $.ajax({
        cache: false,
        async: false,
        type: "POST",
        url: "/ServiceStats.aspx/GetGameDetails",
        contentType: "application/json; charset=utf-8",
        data: "{seasonID:" + seasonID + ", gameID:" + gameID + "}",
        dataType: "json",
        success: function(result) { res = result.d; },
        error: call_error
    });
    return res;
}

function callGetSeasonGamesByGameID(gameID) {
    var res;
    $.ajax({
        cache: false,
        async: false,
        type: "POST",
        url: "/ServiceStats.aspx/GetSeasonGamesByGameID",
        contentType: "application/json; charset=utf-8",
        data: "{gameID:" + gameID + "}",
        dataType: "json",
        success: function(result) { res = result.d; },
        error: call_error
    });
    return res;
}

function callGetCurrentSeasonGamesByTeamID(teamID) {
    var res;
    $.ajax({
        cache: false,
        async: false,
        type: "POST",
        url: "/ServiceStats.aspx/GetCurrentSeasonGamesByTeamID",
        contentType: "application/json; charset=utf-8",
        data: "{teamID:" + teamID + "}",
        dataType: "json",
        success: function(result) { res = result.d; },
        error: call_error
    });
    return res;
}

/* END STATISCTICS */

/* BEGIN DOCUMENTS */
function callGetDocsAll() {
    var res;
    $.ajax({
        cache: false,
        async: false,
        type: "POST",
        url: "/ServiceOther.aspx/GetDocumentsAll",
        contentType: "application/json; charset=utf-8",
        data: "{}",
        dataType: "json",
        success: function(result) { res = result.d; },
        error: call_error
    });
    return res;
}

/* END DOCUMENTS */

/* BEGIN GALLERIES */
function callGetGalleriesByCategoryID(categoryID) {
    var res;
    $.ajax({
        cache: false,
        async: false,
        type: "POST",
        url: "/ServiceGalleries.aspx/GetGalleriesByCategoryID",
        contentType: "application/json; charset=utf-8",
        data: "{categoryID:" + categoryID + "}",
        dataType: "json",
        success: function(result) { res = result.d; },
        error: call_error
    });
    return res;
}

function callGetGalleryItemsByID(galleryID) {
    var res;
    $.ajax({
        cache: false,
        async: false,
        type: "POST",
        url: "/ServiceGalleries.aspx/GetGalleryItemsByID",
        contentType: "application/json; charset=utf-8",
        data: "{galleryID:" + galleryID + "}",
        dataType: "json",
        success: function(result) { res = result.d; },
        error: call_error
    });
    return res;
}

/* END GALLERIES */





function call_error(e) {
    //debugger
    alert("call_error:" + e.ResponseText);
}

