$(function() {    InitializeGlobal();});
function InitializeGlobal()
{
    if ($(".nz-timepicker").length > 0)
    {
        $('.nz-timepicker').timepicker({
            showPeriod: true,
            showLeadingZero: true
        });
    }    

    if ($(".nz-number").length > 0)
        $(".nz-number").autoNumeric({mRound: 'D'});
    
    if ($(".nz-number-decimal").length > 0)    
        $(".nz-number-decimal").autoNumeric({aSep: ',', aDec: '.'});
    
    if ($(".nz-number-currency").length > 0)
        $(".nz-number-currency").autoNumeric({aSep: ',', aDec: '.',aSign:'$'});

    if ($(".com-button").length > 0)    
        $(".com-button").button();
    if ($(".nz-datetime").length > 0)    
        $(".nz-datetime").datepicker();
    if ($(".nz-autogrow").length > 0)    
        $(".nz-autogrow").elastic();

    if ($("a.nz-fancybox").length > 0)
    {
        $("a.nz-fancybox").attr('rel', 'nz-group-images').fancybox({
	    'showCloseButton'	: false,
	    'titlePosition' 	: 'inside',
	    'titleFormat'		: formatTitle
        });    
    }

    if ($('.nz-tooltip').length > 0)
    {
        $('.nz-tooltip').cluetip({
            splitTitle: '|',
            showTitle: false,
            cluetipClass: 'rounded'
        });
    }

    InitializeHTMLEditor();
}

function InitializeHTMLEditor()
{
    var height = 200;
    var width = '';
    
    var config =
        {
            height: height,
            width:width,
            linkShowAdvancedTab: false,
            scayt_autoStartup: true,
            enterMode: Number(2),
            toolbar_Full: [['Bold','Italic','Underline','Strike','NumberedList', 'BulletedList','Outdent','Indent', 'Link', 'Unlink'],
			    ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
                ['Styles','Format','Font','FontSize'],
                ['TextColor','BGColor'],
                ['Maximize', 'ShowBlocks','Table','HorizontalRule', '-','Source']
            
		    ]

        };
            
    if ($(".nz-htmleditor").length > 0)    
        $(".nz-htmleditor").ckeditor(config);
}

function LoadHTMLEditor(ctlName, height,width)
{
    if (typeof(height) == 'undefined')
        height = 200;
    
    if (typeof(width) == 'indefined')
        width = '';
    
    var config =
        {
            height: height,
            width:width,
            linkShowAdvancedTab: false,
            scayt_autoStartup: true,
            enterMode: Number(2),
            toolbar_Full: [['Bold','Italic','Underline','Strike','NumberedList', 'BulletedList','Outdent','Indent', 'Link', 'Unlink'],
			    ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
                ['Styles','Format','Font','FontSize'],
                ['TextColor','BGColor'],
                ['Maximize', 'ShowBlocks','Table','HorizontalRule', '-','Source']
            
		    ]

        };
            
    $("*[id$='" + ctlName + "']").ckeditor(config);
}

function formatTitle(title, currentArray, currentIndex, currentOpts) {
    return '<div id="tip7-title">' + (title && title.length ? '<b>' + title + '</b>' : '' ) + 'Image ' + (currentIndex + 1) + ' of ' + currentArray.length + '</div>';
}

function Nethzah_ShowModelDlg(strURL, windowName, width, height, title, onClosed)
{
    if (width == '')
        width = '75%';
    if (height == '')
        height = '75%';
    
    if (onClosed)
        $('#FancyBoxLink_id').fancybox({'width':width,'height':height, 'href': strURL, 'type': 'iframe', 'onClosed' : eval(onClosed)}); 
    else
        $('#FancyBoxLink_id').fancybox({'width':width,'height':height, 'href': strURL, 'type': 'iframe'}); 
        
    if (!title)
        title = '';
        
    $('#FancyBoxLink_id').attr("title", title); 

    $('#FancyBoxLink_id').trigger('click');
}

function Nethzah_ShowVideo(url)
{
    //$('#FancyBoxVideo_id').fancybox({'href': url}); 
    //$('#FancyBoxVideo_id').trigger('click');
}

function OpenKBArticlePopup(intArticleId)
{
    var strURL = "/Modules/KnowledgeBaseFolder/ViewArticlePopup.aspx?Id=" + intArticleId;
    MotifSoft_OpenNewWindow(strURL, 'ViewArticle', 900, 500);
}

function MSGlobal_OpenDocument(strURL)
{
    MotifSoft_OpenNewWindow(strURL, 'DocumentDetail',670, 450);
}

function ShowRecordInTop(tableid, id)
{
    top.location.href = '/RecordView.aspx?TableId=' + tableid + '&Id=' + id;
}

function OpenChildRecordPopup(strURL)
{
    MotifSoft_OpenNewWindow(strURL, 'ChildRecordPopup', 900, 700);
}

function DisableAllControls(parentControl)
{
    $('#divUserInterest').children('input').each(function() { 
        $(this).attr("disabled", "true"); 
    }); 
}

function GetTasksFromJSON(data)
{
    var tasks = '';
    $.each(data, function(i,item){
        tasks += "<div style='width:100%;clear:both;' >";
        
        tasks += "<div style='width:10%;float:left' >";
        if (item.isdone == 'true')
            tasks += "<input id='chkIsCompleted" + item.id + "' type='checkbox' checked='true' onclick='onSetAsCompleted(" + item.id + ")' />";
        else
            tasks += "<input id='chkIsCompleted" + item.id + "' type='checkbox' onclick='onSetAsCompleted(" + item.id + ")' />";
        tasks += '</div>';
        
        tasks += "<div style='width:80%;float:left;text-align:left' >";
        var subject = item.subject;
        
        if (item.isdone == 'true')
            subject = "<span style='color:#C0C0C0;font-weight=normal;text-decoration:line-through'>" + item.subject + "</span>";
        else if (item.isoverdue == 'true')
            subject = "<span style='color:Red;font-weight:bold'>" + item.subject + "</span>";
        
        tasks += "<a style='text-decoration:none' href='javascript:top.OpenTaskDlg(\"" + item.id + "\");'>" + subject + "</a>";
        tasks += '</div>';

        tasks += "<div style='width:10%;float:left' >";
        tasks += "<img src='/MotifsoftWebShared/Images/Common/Delete.ICO' onclick='onDeleteTask(" + item.id + ");' />";
        tasks += '</div>';

        tasks += '</div>';
        tasks += "<hr class='com-line' />";
    });
    
    return tasks;
}

function GetTemplateView(templateid, id, callbackFunction)
{
    $.ajaxSetup({ cache: false });

    var url = "/AJAXHandlers/GeneralHandler.aspx?GetTemplateView=yes&TemplateId=" + templateid;
    url += "&Id=" + id;

    $.ajax({
        url: url,
        success: function(data) {
            if (data)
            {
                callbackFunction(data)
            }
        }
    });
}

function OpenRecordPopup(intTableId, intFormId, intRecordId, pagetitle, width, height)
{
    var url = '/RecordViewPopUp.aspx?TableId=' + intTableId;
    if ((typeof(intFormId) != 'undefined') && (intFormId != ''))
        url += '&FormId=' + intFormId;
    if (typeof(intRecordId) != 'undefined')
        url += '&Id=' + intRecordId;
        
    if (typeof(pagetitle) == 'undefined')
        pagetitle = '';
        
    if (typeof(width) == 'undefined')
        width = '';

    if (typeof(height) == 'undefined')
        height = '';

    NZ_ShowDynamicIFrameWindow(url, pagetitle, width, height);
}

function NZ_ShowDynamicIFrameWindow(url, pagetitle, width, height)
{
    if (typeof(pagetitle) == 'undefined')
        pagetitle = '';

    if ((typeof(width) == 'undefined') || (width == ''))
        width = $(window).width() - 200;

    if ((typeof(height) == 'undefined') || (height == ''))
        height = $(window).height() - 200;

    var $dialog = $("#nz-dialog-dynamic")
    .html('<iframe style="border: 0px; " src="' + url + '" width="100%" height="100%" ></iframe>')
    .dialog({
        autoOpen: false,
        modal: true,
        height: height,
        width: width,
        title: pagetitle
    });
    $dialog.dialog('open');
}

function NZ_CloseDynamicDialog()
{
    parent.$("#nz-dialog-dynamic").dialog('close');
}

function NZ_LoadPublicCalendar(ctlName, CalendarId)
{
    var url = '/AJAXHandlers/GetJSON.aspx?GetPublicCalendarEvents=yes';
	if (CalendarId != '')
	    url += '&CalendarId=' + CalendarId;

    $('#' + ctlName).fullCalendar({
        events: url,
		eventClick: function(event) {
		    if (event.type == 2)
		    {
		        if (event.displaytypeid == 2)
                    OpenRecordPopup('', event.displaytypevalueid, event.id);
		        else if (event.displaytypeid == 3)
		        {
                    var strURL = "/RecordFolder/TemplateView.aspx?TemplateId=" + event.displaytypevalueid + "&Id=" + event.id;
                    NZ_ShowDynamicIFrameWindow(strURL);
		        }
		        else 
		            OpenRecordPopup(event.tableid, event.id);			    
		    }
		    else
		        OpenAppointmentDlg(event.id);
		},
		loading: function(bool) {
			if (bool) $('#loading').show();
			else $('#loading').hide();
		}
    });
}

function NZ_GetWidth(widthPercent)
{
    var width = $(document).width();
    return parseInt((width/100) * widthPercent);
}

function NZ_GetHeight(heightPercent)
{
    var height = $(document).height();
    return parseInt((height/100) * heightPercent);
}

function NZ_HandleReturnData(json)
{
    var data = $.parseJSON(json);
    if (data.Error != '')
        Global_ShowNotification(data.Error);
    else if (data.RecordId > 0)
        Global_ShowNotification(data.Success);
    else if (data.Success != '')
        Global_ShowNotification(data.Success);
    else
        Global_ShowNotification(json);

    return data;
}

function NZ_FindRecord(type,  callback, qs, ctlName)
{
    var tbl = "<table id='listFindRecord' ></table>";
    tbl += "<div id='pagerlistFindRecord' class='scroll' style='text-align:right;' ></div>";
    tbl += "<input type='hidden' id='hdnFindRecordPrimaryFieldName' >";
    tbl += "<input type='hidden' id='hdnFindRecordNameFieldName' >";

    $("#nz-dialog-dynamic").html(tbl);
    
    $.ajaxSetup({ cache: false });
    
    var url  = '/AJAXHandlers/GetJSONModules.aspx?DoSearch=yes&SearchType=' + type;
    if (typeof(qs) != 'undefined')
        url += qs;

    var dataGrid = new NZ_DataGrid();
    dataGrid.controlId = 'listFindRecord';
    dataGrid.pageSize = 20;
    dataGrid.schemaURL = url;
    dataGrid.primaryFieldCtlName = 'hdnFindRecordPrimaryFieldName';
    dataGrid.nameFieldCtlName = 'hdnFindRecordNameFieldName';
    dataGrid.loadFind = true;
    dataGrid.showLoading = false;
    dataGrid.findCallbackFunctionName = callback;
    if (typeof(ctlName) != 'undefined')
        dataGrid.findBaseCtlName = ctlName;

    dataGrid.showdataondblclick = true;
    dataGrid.dblclickurl = 'javascript:' + callback + '({PrimaryFieldValue})';
    dataGrid.width = NZ_GetWidth(80) - 20;
    dataGrid.load();
}

function NZ_Find_onSelect(ctlName, callback, findBaseCtlName)
{
    var id = jqGridGetSelectedId(ctlName, $("#hdnFindRecordPrimaryFieldName").val());
    if (id != '')
    {
        var name = jqGridGetSelectedColumnValue(ctlName, $("#hdnFindRecordNameFieldName").val());

        eval(callback + "(" + id + ",'" + name + "','" + findBaseCtlName + "');");
        NZ_CloseDynamicDialog();
    }
}

jQuery.fn.autoGrow = function(){
	return this.each(function(){
		// Variables
		var colsDefault = this.cols;
		var rowsDefault = this.rows;
		
		//Functions
		var grow = function() {
			growByRef(this);
		}
		
		var growByRef = function(obj) {
			var linesCount = 0;
			var lines = obj.value.split('\n');
			
			for (var i=lines.length-1; i>=0; --i)
			{
				linesCount += Math.floor((lines[i].length / colsDefault) + 1);
			}

			if (linesCount >= rowsDefault)
				obj.rows = linesCount + 1;
			else
				obj.rows = rowsDefault;
		}
		
		var characterWidth = function (obj){
			var characterWidth = 0;
			var temp1 = 0;
			var temp2 = 0;
			var tempCols = obj.cols;
			
			//obj.cols = 1;
			temp1 = obj.offsetWidth;
			//obj.cols = 2;
			temp2 = obj.offsetWidth;
			characterWidth = temp2 - temp1;
			//obj.cols = tempCols;
			
			return characterWidth;
		}
		
		// Manipulations
		this.style.width = "auto";
		this.style.height = "auto";
		this.style.overflow = "hidden";
		//this.style.width = ((characterWidth(this) * this.cols) + 6) + "px";
		this.style.width = "99%";
		this.onkeyup = grow;
		this.onfocus = grow;
		this.onblur = grow;
		growByRef(this);
	});
};
