﻿//
//

var CodevisionUI = {
    Actions : {
        deleteWidget: function(instanceId)
        {
           Codevision.Web.Framework.WidgetService.DeleteWidgetInstance(instanceId);
           var theDiv = document.getElementById("WidgetPanelsLayout_WidgetContainer" + instanceId + "_Widget");
           theDiv.style.display = "none";
        },

        deletePage: function(pageId)
        {
           Codevision.Web.Framework.PageService.DeletePage(pageId,CodevisionUI.Actions._onDeletePageComplete);

              var tabButton = document.getElementById("Tab"+pageId);
              var tabList = document.getElementById("tabList");
                tabList.removeChild(tabButton);
        },

        _onDeletePageComplete: function(currentPageName)
        {
            document.location.href = '?' + encodeURI(currentPageName);
            //__doPostBack('UpdatePanelTabAndLayout','');
        },

        changePageLayout: function(newLayout)
        {
            Codevision.Web.Framework.PageService.ChangePageLayout(newLayout,CodevisionUI.Actions._onChangePageLayoutComplete);
        },

        _onChangePageLayoutComplete: function(arg)
        {
	        document.location.reload();
        },

        newPage: function(newLayout)
        {
            Codevision.Web.Framework.PageService.NewPage(newLayout, CodevisionUI.Actions._onNewPageComplete);
        },

        _onNewPageComplete: function(newPageName)
        {
            document.location.href = '?' + encodeURI(newPageName);
           //__doPostBack('UpdatePanelTabAndLayout','');
        },
        
        minimizeWidget : function(divId)
        {
            var div = $get(divId);
            div.style.display = "none";
        },

        renamePage: function(newLabel)
        {
            var newPageName = document.getElementById(newLabel).value;
            Codevision.Web.Framework.PageService.RenamePage(newPageName, CodevisionUI.Actions._onRenamePageComplete);
        },
        
        _onRenamePageComplete: function()
        {
            __doPostBack('TabUpdatePanel','');
        },

        changePage: function(pageId, pageName)
        {
            //Codevision.Web.Framework.PageService.ChangeCurrentPage(pageId, OnChangePageComplete);
            document.location.href = '?' + encodeURI(pageName);
        },

        _onChangePageComplete: function(arg)
        {
           __doPostBack('UpdatePanelTabAndLayout','');
        },

        onDrop: function( sender, e )
        {
            var container = e.get_container();
            var item = e.get_droppedItem();
            var position = e.get_position();
            
            //alert( String.format( "Container: {0}, Item: {1}, Position: {2}", container.id, item.id, position ) );
            
            var instanceId = parseInt(item.getAttribute("InstanceId"));
            var columnNo = parseInt(container.getAttribute("columnNo"));
            var row = position;
            Codevision.Web.Framework.WidgetService.MoveWidgetInstance( instanceId, columnNo, row );
        },

        hide: function(id)
        {
            document.getElementById(id).style.display="none";
        },

        showHelp: function()
        {
            var request = new Sys.Net.WebRequest();
            request.set_httpVerb("GET");
            request.set_url('help.aspx');
            request.add_completed( function( executor )
            {
                if (executor.get_responseAvailable()) 
                {
                    var helpDiv = $get('HelpDiv');
                    var helpLink = $get('HelpLink');
                    
                    var helpLinkBounds = Sys.UI.DomElement.getBounds(helpLink);
                    
                    helpDiv.style.top = (helpLinkBounds.y + helpLinkBounds.height) + "px";
                    
                    var content = executor.get_responseData();
                    helpDiv.innerHTML = content;
                    helpDiv.style.display = "block";                       
                }
            });
            
            var executor = new Sys.Net.XMLHttpExecutor();
            request.set_executor(executor); 
            executor.executeRequest();
        }
    }
};

var Utility = 
{
    // change to display:none
    nodisplay : function(e) 
    { 
        if( typeof e == "object") e.style.display = "none"; else if( $get(e) != null ) $get(e).style.display = "none"; 
    },
    // change to display:block
    display : function (e,inline) 
    { 
        if( typeof e == "object") e.style.display = (inline?"inline":"block"); else if( $get(e) != null ) $get(e).style.display = (inline?"inline":"block"); 
    },
    getContentHeight : function()
        {
        if( document.body && document.body.offsetHeight ) {
            return document.body.offsetHeight;
        }
    },


    blockUI : function()
    {
        Utility.display('blockUI');
        var blockUI = $get('blockUI');
    
        if( blockUI != null ) // it will be null if called from CompactFramework
        blockUI.style.height = Math.max( Utility.getContentHeight(), 1000) + "px";    
    },

    unblockUI : function()
    {
        Utility.nodisplay('blockUI');
    }
};

var DeleteWarning =
{
    yesCallback : null,
    noCallback : null,
    _initialized : false,
    init : function()
    {
        if( DeleteWarning._initialized ) return;
        
        var hiddenHtmlTextArea = $get('DeleteConfirmPopupPlaceholder');
        var html = hiddenHtmlTextArea.value;
        var div = document.createElement('div');
        div.innerHTML = html;
        document.body.appendChild(div);
        
        DeleteWarning._initialized = true;
    },
    show : function( yesCallback, noCallback )
    {
        DeleteWarning.init();
        
        Utility.blockUI();
        
        var popup = $get('DeleteConfirmPopup');
        Utility.display(popup);
        
        DeleteWarning.yesCallback = yesCallback;
        DeleteWarning.noCallback = noCallback;
        
        $addHandler( $get("DeleteConfirmPopup_Yes"), 'click', DeleteWarning._yesHandler );
        $addHandler( $get("DeleteConfirmPopup_No"), 'click', DeleteWarning._noHandler );
    },
    hide : function()
    {
        DeleteWarning.init();
        
        var popup = $get('DeleteConfirmPopup');
        Utility.nodisplay(popup);
        
        $clearHandlers( $get('DeleteConfirmPopup_Yes') );
        
        Utility.unblockUI();
        
    },
    _yesHandler : function()
    {
        DeleteWarning.hide();
        DeleteWarning.yesCallback();    
    },
    _noHandler : function()
    {
        DeleteWarning.hide();
        DeleteWarning.noCallback();
    }
};

var DeletePageWarning =
{
    yesCallback : null,
    noCallback : null,
    _initialized : false,
    init : function()
    {
        if( DeletePageWarning._initialized ) return;
        
        var hiddenHtmlTextArea = $get('DeletePageConfirmPopupPlaceholder');
        var html = hiddenHtmlTextArea.value;
        var div = document.createElement('div');
        div.innerHTML = html;
        document.body.appendChild(div);
        
        DeletePageWarning._initialized = true;
    },
    show : function( yesCallback, noCallback )
    {
        DeletePageWarning.init();
        
        Utility.blockUI();
        
        var popup = $get('DeletePageConfirmPopup');
        Utility.display(popup);
        
        DeletePageWarning.yesCallback = yesCallback;
        DeletePageWarning.noCallback = noCallback;
        
        $addHandler( $get("DeletePageConfirmPopup_Yes"), 'click', DeletePageWarning._yesHandler );
        $addHandler( $get("DeletePageConfirmPopup_No"), 'click', DeletePageWarning._noHandler );
    },
    hide : function()
    {
        DeletePageWarning.init();
        
        var popup = $get('DeletePageConfirmPopup');
        Utility.nodisplay(popup);
        
        $clearHandlers( $get('DeletePageConfirmPopup_Yes') );
        
        Utility.unblockUI();
        
    },
    _yesHandler : function()
    {
        DeletePageWarning.hide();
        DeletePageWarning.yesCallback();    
    },
    _noHandler : function()
    {
        DeletePageWarning.hide();
        DeletePageWarning.noCallback();
    }
};

function winopen(url, w, h) 
{
  var left = (screen.width) ? (screen.width-w)/2 : 0;
  var top  = (screen.height) ? (screen.height-h)/2 : 0;

  window.open(url, "_blank", "width="+w+",height="+h+",left="+left+",top="+top+",resizable=yes,scrollbars=yes");
  
  return;
}

function winopen_withlocationbar(url) 
{
 var w = screen.width / 2;
 var h = screen.height /2;
  var left = (screen.width) ? (screen.width-w)/2 : 0;
  var top  = (screen.height) ? (screen.height-h)/2 : 0;

  window.open(url, "_blank");
  
  return;
}

function winopen2(url,target, w, h) 
{
  var left = (screen.width) ? (screen.width-w)/2 : 0;
  var top  = (screen.height) ? (screen.height-h)/2 : 0;

 if(popupWin_2[target] != null)
	if(!popupWin_2[target].closed)
		popupWin_2[target].focus();
	else
		popupWin_2[target] = window.open(url, target, "width="+w+",height="+h+",left="+left+",top="+top+",resizable=yes,scrollbars=yes");
  else
	popupWin_2[target] = window.open(url, target, "width="+w+",height="+h+",left="+left+",top="+top+",resizable=yes,scrollbars=yes");
  
  return;
}


var LayoutPicker =
{
    yesCallback : null,
    noCallback : null,
    type1Callback:null,
    type2Callback:null,
    type3Callback:null,
    type4Callback:null,
    _initialized : false,
    clientID :null,
    init : function()
    {
        if( LayoutPicker._initialized ) return;

        var hiddenHtmlTextArea = $get('LayoutPickerPopupPlaceholder');
        
        var html = hiddenHtmlTextArea.value;
        var div = document.createElement('div');
        div.innerHTML = html;
        document.body.appendChild(div);
        
        LayoutPicker._initialized = true;
    },
    show : function( Type1Callback,Type2Callback,Type3Callback,Type4Callback, noCallback, clientID )
    {   
        LayoutPicker.init();
        
        Utility.blockUI();
        
        var popup = $get('LayoutPickerPopup');
        Utility.display(popup);
        
        LayoutPicker.type1Callback= Type1Callback;
        LayoutPicker.type2Callback= Type2Callback;
        LayoutPicker.type3Callback= Type3Callback;
        LayoutPicker.type4Callback= Type4Callback;
        LayoutPicker.clientID = clientID;
        LayoutPicker.noCallback = noCallback;
        
        $addHandler( $get("SelectLayoutPopup_Cancel"), 'click', LayoutPicker._noHandler );
        $addHandler( $get("SelectLayoutPopup_Type1"), 'click', LayoutPicker._type1Handler );
        $addHandler( $get("SelectLayoutPopup_Type2"), 'click', LayoutPicker._type2Handler );
        $addHandler( $get("SelectLayoutPopup_Type3"), 'click', LayoutPicker._type3Handler );
        $addHandler( $get("SelectLayoutPopup_Type4"), 'click', LayoutPicker._type4Handler );
        
    },
    hide : function()
    {
        LayoutPicker.init();

        
        var popup = $get('LayoutPickerPopup');
        Utility.nodisplay(popup);
        //is there a cleaner way to clear the handlers?
        $clearHandlers( $get('SelectLayoutPopup_Type1') );
        $clearHandlers( $get('SelectLayoutPopup_Type2') );
        $clearHandlers( $get('SelectLayoutPopup_Type3') );
        $clearHandlers( $get('SelectLayoutPopup_Type4') );
        
        Utility.unblockUI();
        
    },

    _type1Handler : function()
    {
        LayoutPicker.hide();
        LayoutPicker.type1Callback();  
    },
    _type2Handler : function()
    {
        LayoutPicker.hide();
        LayoutPicker.type2Callback();    
    },
    _type3Handler : function()
    {
        LayoutPicker.hide();
        LayoutPicker.type3Callback();
    },
    _type4Handler : function()
    {
        LayoutPicker.hide();
        LayoutPicker.type4Callback();
    },

    _noHandler : function()
    {
        LayoutPicker.hide();
        LayoutPicker.noCallback();
    }
};

function validateNIF(sender, args) {
    var nif = args.Value;
    var c;
    var checkDigit = 0;
    
    //Check if is not null, is numeric and if has 9 numbers
    if (nif != null && isNumeric(nif) && nif.length == 9) {
        //Get the first number of NIF
        c = nif.charAt(0);
        //Check firt number is (1, 2, 5, 6, 8 or 9)
        if (c == '1' || c == '2' || c == '5' || c == '6' || c == '8' || c == '9') {
            //Perform CheckDigit calculations
            checkDigit = c * 9;
            var i = 0;
            for (i = 2; i <= 8; i++) {
                checkDigit += nif.charAt(i - 1) * (10 - i);
            }
            checkDigit = 11 - (checkDigit % 11);
            //if checkDigit is higher than ten set it to zero
            if (checkDigit >= 10)
                checkDigit = 0;
            //Compare checkDigit with the last number of NIF
            //If equal the NIF is Valid.
            if (checkDigit == nif.charAt(8)) {
                args.IsValid = true;
            } else {
                args.IsValid = false;
            }

        }
    } else {
        args.IsValid = false;
    }
}

function isNumeric(ObjVal) {
    return /^\d+$/.test(ObjVal);
}

function clickLink(linkid) {
    var linkobj = document.getElementById(linkid);

    if (linkobj.getAttribute('onclick') == null) {
        if (linkobj.getAttribute('href')) document.location = linkobj.getAttribute('href');
    }
    else linkobj.onclick();
}

function pageUnload()
{

}

function enforceDateValidation(sender, args) {
    var controlId = sender.controlId;
    var value = sender.value;
    var operation = sender.operation;

    var tbToValidate = document.getElementById(controlId);
    var compareDate = null;
    
    if (tbToValidate != null && tbToValidate.value != "") {
        compareDate = tbToValidate.value.replace(/-/g, "/");
    }

    if (value != null && value != "") {
        compareDate = value.replace(/-/g, "/");
    }
    
    if (compareDate != null && args.Value != "") {
        var currentDate = args.Value.replace(/-/g, "/");

        var compareDateParts = compareDate.split("/");
        var currentDateParts = currentDate.split("/");

        var compareDateStr = compareDateParts[2] + compareDateParts[1] + compareDateParts[0];
        var currentDateStr = currentDateParts[2] + currentDateParts[1] + currentDateParts[0];
    
        switch (operation) {
            case "Equal":
                args.IsValid = parseInt(currentDateStr) == parseInt(compareDateStr);
                break;

            case "NotEqual":
                args.IsValid = parseInt(currentDateStr) != parseInt(compareDateStr);
                break;

            case "GreaterThan":
                args.IsValid = parseInt(currentDateStr) > parseInt(compareDateStr);
                break;

            case "GreaterThanEqual":
                args.IsValid = parseInt(currentDateStr) >= parseInt(compareDateStr);
                break;

            case "LessThan":
                args.IsValid = parseInt(currentDateStr) < parseInt(compareDateStr);
                break;

            case "LessThanEqual":
                args.IsValid = parseInt(currentDateStr) <= parseInt(compareDateStr);
                break;
        }

        return;
    }

    args.IsValid = true;
}

/* This function resolves postback problems with the FCKeditor and Firefox */
function FCKUpdateLinkedField(id) {
    try {
        if (typeof (FCKeditorAPI) == "object") {
            FCKeditorAPI.GetInstance(id).UpdateLinkedField();
        }
    }
    catch (err) {
    }
}

/*function expandAllPanels(parentId, openOrClose) {
    var parent = $get(parentId);

    for (var obj in parent.childNodes) {
        if (obj.)
    }
}*/

// Sys.Application.add_load(AjaxControlToolkit.AccordionBehavior.prototype._expandAllPanes =
function expandAllPanes(openOrClose) {
    this._changeSelectedIndex(-1, true);

    for (var i = 0; i < this._panes.length; i++) {
        // Get the animation for each pane (creating it on demand if it doesn't already exist)

        var pane = this._panes[i]; var animation = this._getAnimation(pane);
        animation._opening = openOrClose;
        var open = null;
        var close = null;

        // Stop any animations that are still playing (i.e. that haven't finished
        // opening or closing from changing previous panes)
        if (animation.get_isPlaying()) {
            animation.stop();
        }

        // Get the pane ready to be animated by setting
        this._startPaneChange(pane, animation._opening);

        // Setup the fade effect if we are using it
        if (this._fadeTransitions) {
            animation._fade.set_effect(animation._opening ? AjaxControlToolkit.Animation.FadeEffect.FadeIn :
                AjaxControlToolkit.Animation.FadeEffect.FadeOut);

        }

        // Set the length animation and the target
        if (this._autoSize === AjaxControlToolkit.AutoSize.Fill) {
            animation.set_target(pane.content._original);
            animation._length.set_startValue(CommonToolkitScripts.getContentSize(pane.content._original).height);
            animation._length.set_endValue(animation._opening ? this._getRemainingHeight(true) : 0);
        } else {
            animation.set_target(pane.content);
            animation._length.set_startValue(pane.content.offsetHeight);
            animation._length.set_endValue(animation._opening ? this._getRemainingHeight(false) : 0);
        }

        //Open or Close all the pannels

        if (openOrClose) {
            animation._opening = true;
            open = animation;

            if (open) {
                open.play();
            }
        } else {
            animation._opening = false;
            close = animation;

            if (close) {
                close.play();
            }
        }
    }
}

function toggle_visibility(id) {
    var e = document.getElementById(id);
    if (e.style.display == 'block')
        e.style.display = 'none';
    else
        e.style.display = 'block';
}

function clearForm(id) {
    $(id).each(function () {
        if (this.type == 'select-one')
            this.selectedIndex = 0;
        else
            this.value = '';
    });
}

function getNumberFromChar(letter) {

    switch (letter) {
        case '0': return 0;
        case '1': return 1;
        case '2': return 2;
        case '3': return 3;
        case '4': return 4;
        case '5': return 5;
        case '6': return 6;
        case '7': return 7;
        case '8': return 8;
        case '9': return 9;
        case 'A': return 10;
        case 'B': return 11;
        case 'C': return 12;
        case 'D': return 13;
        case 'E': return 14;
        case 'F': return 15;
        case 'G': return 16;
        case 'H': return 17;
        case 'I': return 18;
        case 'J': return 19;
        case 'K': return 20;
        case 'L': return 21;
        case 'M': return 22;
        case 'N': return 23;
        case 'O': return 24;
        case 'P': return 25;
        case 'Q': return 26;
        case 'R': return 27;
        case 'S': return 28;
        case 'T': return 29;
        case 'U': return 30;
        case 'V': return 31;
        case 'W': return 32;
        case 'X': return 33;
        case 'Y': return 34;
        case 'Z': return 35;

    }
}
