﻿var _PortalID;
var _UserID;
var _SiteID;
var _ModulePath;
var _PageID = '';
var _PageTitle = '';
var _ModuleID = '';
var _skinname;
var _SiteAdmin;
var _initload = true;
var _privateurl;
var _SiteSkin;
var _UpdateProfile = false;
var objFetchSite = null;
var _IsPublic;

$(document).ready(function() {

    Shadowbox.init({
        skipSetup: true
    });

    // Get server variables
    _PortalID = dnn.getVar('PortalID');
    _UserID = dnn.getVar('UserID');
    _SiteID = dnn.getVar('SiteID');
    _ModulePath = dnn.getVar('ModulePath');
    _SiteAdmin = dnn.getVar('SiteAdmin');
    _IsEditable = dnn.getVar('IsEditable');
    _privateurl = dnn.getVar('privateurl');
    
    $('#lnkhome').attr("href", dnn.getVar('homeurl'));

    if (dnn.getVar('districtadmin') == 'False') {
        $('#lidistrictsettings').empty();
    }

    if (location.hash != '') {
        $.each(location.hash.replace(/^.*#/, '').split('_'), function() {
            var key = this.split('.')[0];
            var val = this.split('.')[1];

            if (/^[0-9.]+$/.test(val)) {
                val = parseFloat(val);
            }
            else if (/^[0-9]+$/.test(val)) {
                val = parseInt(val);
            };

            switch (key) {
                case "site":
                    _SiteID = val;
                    break
                case "pid":
                    _PageID = val;
                    break
                case "mid":
                    _ModuleID = val;
                    break
            }
        });
    }

    initSite();

});

function initSite() {
    
    if (_SiteID > 0) {
        FetchSite(_SiteID);
    }
    else if (_UserID > 0) {
    
        FetchSiteByUser(_UserID)
    }

    setheight();

    // hide mask, display site
    $('#mask').fadeOut("slow");
    $('#body_inner').fadeIn("slow");
    $('#footer').fadeIn("slow");
}
    
    function setheight() {
        // Set content height based on window size
        var _contentheight = ($(window).height() - 72) + 'px';
        $('#mask').css({ "height": _contentheight });
    }

    function FetchSite() {
        
        // abort any current FetchListings     
        if (objFetchSite) {objFetchSite.abort();}
        
        objFetchSite = $.ajax({
            type: "POST",
            url: "../../../../desktopmodules/sitebuilder/components/WebService.asmx/FetchSite",
            // pass parameters to webmethod
            data: "{PortalID: " + _PortalID + ", SiteID: " + _SiteID + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                // if data is returned, iterate through response
            if (null != msg) {
                    _UpdateProfile = (msg.ClassCount < 1);
                    LoadSite(msg);
                }
                else {
                    window.location = dnn.getVar("homeurl") + "?msgtype=error&msg=Site not found.  Please verify the address and contact your site administrator if the problem persists.";
                }
            }
        });
    }

    function FetchSiteByUser(_UserID) {
        // abort any current FetchListings     
        if (objFetchSite) {objFetchSite.abort();}

        objFetchSite = $.ajax({
            type: "POST",
            url: "/desktopmodules/sitebuilder/components/WebService.asmx/FetchSiteByUser",
            // pass parameters to webmethod
            data: "{PortalID: " + _PortalID + ", UserID: " + _UserID + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                // if data is returned, iterate through response
                if (null != msg) {
                    _UpdateProfile = (msg.ClassCount < 1);
                    _SiteID = msg.SiteID;
                    LoadSite(msg);
                }
                else {
                    // if no site found, call webservice and create a blank site
                    $.ajax({
                        type: "POST",
                        url: "/desktopmodules/sitebuilder/components/WebService.asmx/AddSite",
                        // pass parameters to webmethod
                        data: "{PortalID: " + _PortalID + ", OwnerID: " + _UserID + "}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function(msg) {
                            _UpdateProfile = (msg.ClassCount < 1);
                            LoadSite(msg);
                        }
                    });
                }
            }
        });
    }

    function LoadSite(msg) {
           
        if (_UserID == msg.OwnerID || _IsEditable == 'True') {
            _IsEditable = 'True';
            $('#globalheader').show();
         }
        else {
            $('#globalheader').empty();
        }

        //LoadSkin
        if (msg.Skin == undefined || msg.Skin == '') {
            _SiteSkin = 'default';
        }
        else
        {
            _SiteSkin = msg.Skin;
        }
        
        _IsPublic = msg.IsPublic;
        
        $('#body_inner').load(_ModulePath + 'skins/' + _SiteSkin + '/page.html', function() {
            if (_IsEditable == 'True') {
                $('#lnkdistrictsettings').attr("href", dnn.getVar('districtsettingsurl'));
                $('#lnksitesettings').attr("href", _privateurl + '?skin=' + _SiteSkin + '&mode=site&siteid=' + _SiteID);
                Shadowbox.setup($('.Shadowbox'), {
                    onClose: FetchSite
                });
            }

            $('#name-text a').html(msg.Title);
            $('#slogan-text').html(msg.TagLine);
            $('.art-Footer-text').html($('#skinfooter').html());

            FetchPages(_SiteID);
        });
      
        $('head').append('<link rel="stylesheet" href="' + _ModulePath + 'skins/' + _SiteSkin + '/style.css" type="text/css" />');
        $('head').append('<!--[if IE 7]><link rel="stylesheet" href="' + _ModulePath + 'skins/' + _SiteSkin + '/style.ie7.css" type="text/css" media="screen" /><![endif]-->');
        $('head').append('<!--[if IE 6]><link rel="stylesheet" href="' + _ModulePath + 'skins/' + _SiteSkin + '/style.ie6.css" type="text/css" media="screen" /><![endif]-->');
        $('head').append('<script type="text/javascript" src="' + _ModulePath + 'skins/' + _SiteSkin + '/script.js"></script>');
    }

function FetchPages() {
    
    var sysMenuConfig = $('#sysMenuConfig').html();

    $.ajax({
        type: "POST",
        url: "../../../../desktopmodules/sitebuilder/components/WebService.asmx/FetchPages",
        // pass parameters to webmethod
        data: "{SiteID: " + _SiteID + ", UserID: " + _UserID + ", IsEditable: '" + _IsEditable + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            //  clear all current pages
            $('ul.pagenav').empty();
            // if data is returned, iterate through response
            if (msg != '') {
                for (var i = 0; i < msg.length; i++) {
                    if (_IsEditable == 'True') {
                        if (msg[i].IsPublic) {
                            $('<li><span><a class="lnkpage" href="#" rel="' + msg[i].PageID + "_" + msg[i].Title + '">' + sysMenuConfig.replace('MenuItem', msg[i].Title) + '</a></span></li>').appendTo('ul.pagenav');
                        }
                        else {
                            $('<li class="noshow"><span><a class="lnkpage" href="#" rel="' + msg[i].PageID + "_" + msg[i].Title + '">' + sysMenuConfig.replace('MenuItem', msg[i].Title) + '</a></span></li>').appendTo('ul.pagenav');
                        }
                        if (_PageID == '' || _PageID == -1) { _PageID = msg[i].PageID; }
                        if (_PageID == msg[i].PageID) { _PageTitle = msg[i].Title; }
                    }
                    else if (msg[i].IsPublic) {
                        $('<li><a class="lnkpage" href="#" rel="' + msg[i].PageID + "_" + msg[i].Title + '">' + sysMenuConfig.replace('MenuItem', msg[i].Title) + '</a></li>').appendTo('ul.pagenav');
                        if (_PageID == '' || _PageID == -1) { _PageID = msg[i].PageID; }
                        if (_PageID == msg[i].PageID) { _PageTitle = msg[i].Title; }
                    }
                }
                $('ul.pagenav li:last a').addClass("last");

                //  clear any existing listeners
                $('.pagenav a').unbind('click');
                //  add listeners for click - fetch clicked page's modules
                $('.lnkpage').click(function() {
                    _ModuleID = -1;  //clear current moduleid
                    _PageID = $(this).attr("rel").split('_')[0];  // set clicked pageid
                    _PageTitle = $(this).attr("rel").split('_')[1]; // set clicked page title
                    $('.lnkpage').removeClass("active");
                    $(this).addClass("active");
                    FetchPage();  // load the page
                    return false
                });
            }

            if (_IsEditable == 'True') {
                $('#lnkaddpage').attr("href", _privateurl + '?skin=' + _SiteSkin + '&mode=page&siteid=' + _SiteID);
                Shadowbox.setup($('#lnkaddpage'), {
                    onClose: FetchPages
                });
            }

            FetchPage();
            $('ul.pagenav li:first a').addClass("active");
            
        }
    });
}

function FetchPage() {
    $('#modulecontainer').empty();
    $('.title').html(_PageTitle);
    if (_IsEditable == 'True') {
        $('.title').html('<a rel="shadowbox;player=iframe;" class="imgedit" href="' + _privateurl + '?skin=' + _SiteSkin + '&mode=page&siteid=' + _SiteID + '&pageid=' + _PageID + '"><img class="imgedit" src="' + _ModulePath + 'images/edit.gif" alt="edit"></a>' + _PageTitle);
    }
    else {
        $('.title').html(_PageTitle);
    }

    $.ajax({
        type: "POST",
        url: "../../../../desktopmodules/sitebuilder/components/WebService.asmx/FetchModules",
        // pass parameters to webmethod
        data: "{PageID: " + _PageID + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            // clear all current modules
            $('ul.modulenav').empty();
            // if data is returned, iterate through response
            if (msg != '') {
                for (var i = 0; i < msg.length; i++) {
                    if (_IsEditable == 'True') {
                        if (msg[i].IsPublic) {
                            $('<li><a rel="shadowbox;player=iframe" class="imgedit" href="' + _privateurl + '?skin=' + _SiteSkin + '&mode=module&siteid=' + _SiteID + '&pageid=' + _PageID + '&moduleid=' + msg[i].ModuleID + '&ModuleType=' + msg[i].ModuleType + '&ModuleTypeID=' + msg[i].ModuleTypeID + '"><img class="imgedit" src="' + _ModulePath + 'images/edit.gif" alt="edit"></a><a class="lnkmodule" href="#" rel="' + msg[i].ModuleID + '">' + msg[i].Title + '</a></li>').appendTo('ul.modulenav');
                        }
                        else {
                            $('<li class="noshow"><a rel="shadowbox;player=iframe" class="imgedit" href="' + _privateurl + '?skin=' + _SiteSkin + '&mode=module&siteid=' + _SiteID + '&pageid=' + _PageID + '&moduleid=' + msg[i].ModuleID + '&ModuleType=' + msg[i].ModuleType + '&ModuleTypeID=' + msg[i].ModuleTypeID + '"><img class="imgedit" src="' + _ModulePath + 'images/edit.gif" alt="edit"></a><a class="lnkmodule" href="#" rel="' + msg[i].ModuleID + '">' + msg[i].Title + '</a></li>').appendTo('ul.modulenav');
                        }
                    }
                    else if (msg[i].IsPublic) {
                        $('<li><a class="lnkmodule" href="#" rel="' + msg[i].ModuleID + '">' + msg[i].Title + '</a></li>').appendTo('ul.modulenav');
                    }
                }

                $('#modulecontainer').empty();
                $('.lnkmodule').unbind('click');
                $('.lnkmodule').click(function() {
                    _ModuleID = $(this).attr("rel");
                    $('.PostHeader').html($(this).html());
                    
                    location.hash = 'site.' + _SiteID + '_pid.' + _PageID + '_mid.' + _ModuleID;
                    FetchModule();
                    return false
                });

                if (_ModuleID == -1 || _ModuleID == '') {
                    $('.PostHeader').html(msg[0].Title);
                    _ModuleID = msg[0].ModuleID;
                }

                FetchModule();

                if (_IsPublic === false) {
                    RaiseMessage("info", "This site is currently hidden. To publish, modify your site settings.", "msgcontainer");
                }

                if (_UpdateProfile === true) {
                    RaiseMessage("info", "No Classes found for this site.  Please update your site settings.", "msgcontainer");
                }
            }
            if (_IsEditable == 'True') {
                FetchModulesForEdit();

                Shadowbox.setup($('a.imgedit'), {
                    onClose: FetchPage
                });
            }
        }
    });
}

function FetchModulesForEdit() {
    var options= '';
    $.ajax({
        type: "POST",
        url: "../../../../desktopmodules/sitebuilder/components/WebService.asmx/FetchModulesByPortal",
        // pass parameters to webmethod
        data: "{PortalID: " + _PortalID + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            // if data is returned, iterate through response
            if (null != msg) {
                $('ul#addmodules').empty();

                if (msg.length == 0) {
                    RaiseMessage("info", "No modules have been enabled for this site.  Please contact your site administrator.", "msgcontainer");
                }
                else {
                    for (var i = 0; i < msg.length; i++) {
                        $('<li><a class="lnkaddmodule" href="' + _privateurl + '?skin=' + _SiteSkin + '&mode=module&siteid=' + _SiteID + '&pageid=' + _PageID + '&ModuleType=' + msg[i].ModuleType + '&ModuleTypeID=' + msg[i].ModuleTypeID + '">' + msg[i].ModuleType + '</a></li>').appendTo('ul#addmodules');
                    }

                    Shadowbox.setup($('.lnkaddmodule'), {
                        onClose: FetchPages
                    });

                    $('#lnkaddmodules').unbind().click(function() { $('ul#addmodules').slideToggle(); });

                    $('.lnkaddmodule').click(function() {
                        if (_PageID == -1) {
                            RaiseMessage("info", "You must first add a new page.", "msgcontainer");
                        }
                        else {
                            if ($('ul#addmodules').is(':visible')) { $('ul#addmodules').hide(); }
                        }
                        return false;
                    });
                }
            }
        }
    });
}

function FetchModule() {
    
    $('#modulecontainer').empty();
    objFetchSite = $.ajax({
        type: "POST",
        url: "../../../../desktopmodules/sitebuilder/components/WebService.asmx/FetchModule",
        // pass parameters to webmethod
        data: "{ModuleID: " + _ModuleID + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
        $('#modulecontainer').load(_ModulePath + 'modules/' + msg.ModuleType + '/' + msg.ModuleType + '.htm?ModuleID=' + _ModuleID, function() {
            window['init_' + msg.ModuleType](_ModuleID, _IsEditable); 
            SetEditControls(_IsEditable, _ModuleID, msg.ModuleType); });
        }
    });

    location.hash = 'site.' + _SiteID + '_pid.' + _PageID + '_mid.' + _ModuleID; 
}

function RaiseMessage(msgtype, msg, placeholder) {
    // add message div to placeholder
    $('#' + placeholder).empty();
    $("<div id='" + placeholder + "_pnlmsg' class='" + msgtype + "'><div class='leftcol'>" + msg + "</div><div class='rightcol'><a id='" + placeholder + "_close' href=''><img alt='x' src='/desktopmodules/sitebuilder/images/close.png' /></a></div></div>").fadeIn("slow").appendTo('#' + placeholder);
    $('#' + placeholder + '_close').click(function() {
        $(this).unbind("click");
        $(this).fadeOut("slow", function() { $('#' + placeholder).empty(); });
        return false;
    });
}

function LoadInitialWelcome() {
    RaiseMessage("info", "Welcome to Your New Site!", "msgcontainer");
}

function Set_Cookie(name, value, expires, path, domain, secure) {
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime(today.getTime());

    if (expires) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date(today.getTime() + (expires));

    document.cookie = name + "=" + escape(value) + ((expires) ? ";expires=" + expires_date.toGMTString() : "") + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ((secure) ? ";secure" : "");
}

function Get_Cookie(check_name) {
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split(';');
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f

    for (i = 0; i < a_all_cookies.length; i++) {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split('=');


        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

        // if the extracted name matches passed check_name
        if (cookie_name == check_name) {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if (a_temp_cookie.length > 1) {
                cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
            }
            // note that in cases where cookie is initialized but no value, null is returned
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if (!b_cookie_found) {
        return null;
    }
}

// this deletes the cookie when called
function Delete_Cookie(name, path, domain) {
    if (Get_Cookie(name)) document.cookie = name + "=" + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function truncate(str, length, suffix, id) {
    if (str.length <= length) {
        return str;
    }

    if (suffix == undefined) {
        suffix = '...';
    }
    

    if (id != undefined) {
        suffix = '<a class="lnkmore" rel="' + id + '" href="#">' + suffix + '</a>'
    }

    return str.substr(0, length).replace(/\s+?(\S+)?$/g, '') + suffix;
};


var dateFormat = function() {
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function(val, len) {
		    val = String(val);
		    len = len || 2;
		    while (val.length < len) val = "0" + val;
		    return val;
		};

    // Regexes and supporting functions are cached through closure
    return function(date, mask, utc) {
        var dF = dateFormat;

        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }

        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date;
        if (isNaN(date)) throw SyntaxError("invalid date");

        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }

        var _ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
			    d: d,
			    dd: pad(d),
			    ddd: dF.i18n.dayNames[D],
			    dddd: dF.i18n.dayNames[D + 7],
			    m: m + 1,
			    mm: pad(m + 1),
			    mmm: dF.i18n.monthNames[m],
			    mmmm: dF.i18n.monthNames[m + 12],
			    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",
			    Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
			    o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
			    S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

        return mask.replace(token, function($0) {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
} ();

// Some common format strings
dateFormat.masks = {
    "default": "ddd mmm dd yyyy HH:MM:ss",
    shortDate: "m/d/yy",
    mediumDate: "mmm d, yyyy",
    longDate: "mmmm d, yyyy",
    fullDate: "dddd, mmmm d, yyyy",
    shortTime: "h:MM TT",
    mediumTime: "h:MM:ss TT",
    longTime: "h:MM:ss TT Z",
    isoDate: "yyyy-mm-dd",
    isoTime: "HH:MM:ss",
    isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
    monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function(mask, utc) {
    return dateFormat(this, mask, utc);
};

function SetEditControls(editable, moduleid, moduletype) {

    if (editable == 'True') {
        $('#lnkaddnew').attr("href", _privateurl + '?skin=' + _SiteSkin + '&moduleid=' + moduleid + '&pageid=' + _PageID + '&siteid=' + _SiteID + '&mode=' + moduletype);
        $('#lnksettings').attr("href", _privateurl + '?skin=' + _SiteSkin + '&moduleid=' + moduleid + '&pageid=' + _PageID + '&siteid=' + _SiteID + '&mode=' + moduletype + '_settings');
        Shadowbox.setup($('.lnkedit'), {
            onClose: FetchModule
        });
        $('#controls').show();
    }
    else {
        $('#controls').empty();
    }
}
