﻿        var boxes = {};
    
    
        var Box = function(){
        
        }
        Box.prototype.id;
        Box.prototype.title = "Untitled";
        Box.canEdit = false;
        Box.prototype.isMinimized = false;
        Box.prototype.isEditOpen = false;
        Box.prototype.canEdit = false;
        Box.prototype.debug = false;
        
        Box.prototype.getBody = function(){
            return document.getElementById(this.id+"Body");
        }
        
        Box.prototype.clearNotices = function(){
            var ee = $("#"+this.boxId+"_error");
            ee.html("");
            ee.hide();
        }
        
        Box.prototype.error = function(error){
            var ee = $("#"+this.boxId+"_error");
            //alert(error._exceptionType);
            if(error._exceptionType == "Mofus.Exceptions.UserAuthorizationException"){
                ee.html("This action requires that you <a href=\"Membership/Login.aspx?ReturnUrl=~/Default.aspx\">sign in</a> or <a href=\"Membership/Register.aspx\">register</a>");
            }else{
                ee.html(error._message);
            }
            ee.addClass("error");
            ee.show();
        }
        
        Box.prototype.getEdit = function(){
            return document.getElementById(this.id+"_edit");
        }
        
        Box.prototype.getEditButton = function(){
            return document.getElementById(this.id+"_EditButton");
        }
        
        Box.prototype.getMinimizeButton = function(){
            return document.getElementById(this.id+"_MinimizeButton");
        }
        
        Box.prototype._onData = function(){
            $(this.getBody()).removeClass("ajax-waiting");
        }
        
        Box.prototype.update = function(){
            if(!this.isMinimized){
                var body = this.getBody();
                if(body!=null){
                    var curr = body.innerHTML.split(" ").join("").split("\n").join("").split("\r").join("").split("\t").join("");

                    //if(curr == "" || curr == "undefined" || curr == null){
                        body.innerHTML = "Loading...";
                    //}
                    $(this.getBody()).addClass("ajax-waiting");
                    
                    PageMethods.GetDataForPortlet(this.id, this.onData, this.onDataError, this);
                }
            }else{
                this._onToggleMinimize();
            }
            this._updateEdit();
        }
        
        Box.prototype.onDataError = function(errorObj, context){
            if(this.getBody){
                $(this.getBody()).removeClass("ajax-waiting");
                //if(this.debug){
                    Box.showError(errorObj);
                //}else{
               // /    window.location = window.location;
               // }
           }else{
                alert("Error loading " + context.title);
           }
        }
        
        Box.prototype.toggleMinimize = function(){
            this.clearNotices();
            PageMethods.TogglePortletMinimize(this.id, Box.onToggleMinimize, Box.onToggleMinimizeError, this.id);
            this._onToggleMinimize();
        }
        
        Box.prototype._onToggleMinimize = function(){
            var body = boxes[this.id].getBody();
            var button = boxes[this.id].getMinimizeButton();
            if(boxes[this.id].isMinimized){
                body.style["display"] = "none";
                button.className = "minimize-button-closed";
            }else{
                body.style["display"] = "block";
                button.className = "minimize-button-open";
            }
            this._updateEdit();
        }
        
        Box.onToggleMinimize = function(currentState, boxId){
            boxes[boxId].isMinimized = currentState;
            boxes[boxId]._onToggleMinimize();
            boxes[boxId].update();
        }
        
        Box.onToggleMinimizeError = function(){
            Box.showError(arguments[0]);
        }
        
        Box.prototype.toggleEditBox = function(){
            this.isEditOpen = !this.isEditOpen;
            this._updateEdit();
        }
        
        Box.prototype.showEdit = function(){
            this.isEditOpen = true;
            this._updateEdit();
        }
        
        Box.prototype.hideEdit = function(){
            this.isEditOpen = false;
            this._updateEdit();
        }
        
        Box.prototype.onData = function(){};
        
        Box.prototype.loadData = function(){
            this.clearNotices();
            $(this.getBody()).innerHTML = "Loading...";
            $(this.getBody()).addClass("ajax-waiting");
            
            $.ajax({
               type: "POST",
               url: "Default.aspx/GetDataForPortlet",
               data: Sys.Serialization.JavaScriptSerializer.serialize({id:this.boxId}),
               contentType:"application/json",
               dataType:"json",
               success: function(resp, status){
                    //alert("des1:"+resp);
                    var response = Sys.Serialization.JavaScriptSerializer.deserialize(resp);
                    //alert("des2:"+this.data);
                    var request = Sys.Serialization.JavaScriptSerializer.deserialize(this.data);
                    var box =  boxes[request.id];
                    var body = $(box.getBody());
                    box.onData(response);
                    body.removeClass("ajax-waiting");
                    doPageDataUpdated();
                }
             });
        }
        
        
        Box.prototype.onEditFormShow = function(){
        
        }

        Box.prototype.onEditFormHide = function(){
        
        }

        Box.prototype._updateEdit = function(){
            var edit = this.getEdit();
            var editButton = this.getEditButton();
            if(edit){
                if(this.isEditOpen && !this.isMinimized){
                    edit.style["display"] = "block";
                    boxes[this.boxId].onEditFormShow();
                }else{
                    edit.style["display"] = "none";
                    boxes[this.boxId].onEditFormHide();
                }
               // edit.style["display"] = (this.isEditOpen && !this.isMinimized)? "block" : "none";
                
             
            }
            if(editButton){
                editButton.style["visibility"] = (this.isMinimized || !this.canEdit)? "hidden" : "visible";
                editButton.innerHTML = (this.isEditOpen)? "Done" : "Add" ;
            }
        }
         
        Box.prototype.close = function(){
            PageMethods.ClosePortlet(this.id, Box.onClose, Box.onCloseError, this.id);
        }
        
        Box.getBoxElementById = function(id){
            var boxenodes = $(".box");
            for(var i=0;i<boxenodes.length;i++){
                if(boxenodes[i].id.indexOf(id) > -1){
                    return boxenodes[i];
                }
            }
            return null;
        }
        
        Box.onClose = function(noIdea, id, callingFunction){
            var box = Box.getBoxElementById(id);
            $(box).remove();
           // box.style["display"] = "none";
        }
        
        Box.onCloseError = function(e, id){
            Box.showError(arguments[0]);
        }
        

        Box.showError = function (errorObj){
            var sb = new Array();
            if(errorObj._timedOut){
                alert("server times out");
            }else{
                sb.push("Error: " + errorObj._statusCode);
                sb.push("\n\n");
                sb.push(errorObj._message);
                sb.push("\n\n");
                sb.push(errorObj._stackTrace);
                sb.push("\n\n");
                sb.push(errorObj._exceptionType);
            }
            alert("ERROR:"+sb.join(""));
        }

        /***
            BOX static draw methods
        ***/
        
        Box.formatEventItem = function(evt, onEventLink, showDate, showTime){
            var sb = new Array();
            var startDate = new Date(evt.Start.getYear(), evt.Start.getMonth(), evt.Start.getDate(), evt.Start.getHours(), evt.Start.getMinutes()+evt.Start.getTimezoneOffset());
            sb.push("<tr class=\"event\">");
            if(showDate){
                sb.push("    <td class=\"date\">"+startDate.localeFormat("MMM d")+"</td>");
            }
            if(showTime){
                //sb.push("    <td class=\"time\">"+evt.End.localeFormat(Sys.CultureInfo.CurrentCulture.dateTimeFormat.ShortTimePattern)+"</td>");
                sb.push("    <td class=\"time\">" + startDate.localeFormat(Sys.CultureInfo.CurrentCulture.dateTimeFormat.ShortTimePattern)+"</td>");
            }
            sb.push("    <td class=\"title\" >");
            //sb.push("        <a href='" + onEventLink(evt) + "' onmouseout=\"Mofus.UI.MoreInfoHover.hide();\"  onmouseover=\"Mofus.UI.MoreInfoHover.showEventInfo('"+ evt.Id + "')\">"+evt.Description+"</a>");
            sb.push("        <a href='" + onEventLink(evt) + "' title=\""+evt.Description+"\" rel=\""+_onEventRel(evt)+"\" class=\"event-link tooltip\">"+evt.Description+"</a>");
            
            sb.push("    </td>");
            sb.push(" </tr>");
            return sb.join("");
        }
        
        Box.formatEventList = function(events, onEventLink, showDate, showTime){
            var sb = new Array();
            sb.push("<table cellspacing=\"0\" cellpadding=\"0\">");
            for(var i=0;i<events.length;i++){
                var evt = events[i];
                sb.push(Box.formatEventItem(evt, onEventLink, showDate, showTime));
            }
            sb.push(" </table>");
            return sb.join("");
        }
        
        Box.formatSectionItem = function(section, boxId, index, len, onSectionLink, onSectionRel, sectionCssClass){
            var sb = new Array();

            sb.push("<h3 class=\"event-section-head\" sectionId='"+ section.Id+"'\" boxId=\""+ boxId +"\" index=\""+ index +"\">");
            
            sb.push("<span class=\"section-menu\"></span>");
            
            sb.push("<a class=\"event-section-title "+((sectionCssClass)? sectionCssClass : "")+"\" href=\"" + onSectionLink(section) + "\" " + ((onSectionRel)? "rel=\""+onSectionRel(section)+"\"" : "") + "  sectionId='"+ section.Id+"'\" boxId=\""+ boxId +"\" index=\""+ index +"\" length=\""+ len +"\" title=\"right click for options\"  >"+section.Title+"</a>");

            sb.push("</h3>");
            return sb.join("");
        }
        
        Box.formatDateSectionItem = function(section, boxId, index){
            var sb = new Array();
            sb.push("<h3>");
            sb.push("<span class=\"date-description\" style=\"float: left;\">"+section.Title+"</span>");
            sb.push("<span class=\"date\" style=\"float: right;\">"+section.Subtitle+"</span>");
            sb.push("</h3>");
            sb.push("<br style=\"clear: both;\">");
            return sb.join("");
        }
        
        Box.formatSections = function(sections, boxId, onSectionLink, onEventLink, onSectionRel, sectionCssClass){
            var sb = new Array();
            sb.push("<div class=\"event-list\">");
            for(var i=0;i<sections.length;i++){
                sb.push(Box.formatSectionItem(sections[i], boxId, i, sections.length, onSectionLink, onSectionRel, sectionCssClass));
                sb.push(Box.formatEventList(sections[i].Events, onEventLink, true , true));   
            }
            sb.push("</div>");
            var box = $("#"+box);
            //$('.event-link').cluetip({dropShadow:false, showTitle:false, titleAttribute:'tip', cluetipClass: 'jtip', arrows: true});
            return sb.join("");
            
        }
        
        Box.formatDateSections = function(sections, boxId, onEventLink){
            var sb = new Array();
            sb.push("<div class=\"event-list\">");
            for(var i=0;i<sections.length;i++){
                sb.push(Box.formatDateSectionItem(sections[i], boxId, i));
                sb.push(Box.formatEventList(sections[i].Events, onEventLink, false, true));
            }
            sb.push("</div>");
            var box = $("#"+boxId);
            //$('.event-link', box).cluetip({dropShadow:false, showTitle:false, titleAttribute:'tip', cluetipClass: 'jtip', arrows: true});
            return sb.join("");
}