var radEditor;
var divEditor;
var divEditorContent;
var radCallbackId;
var radEditorDock;
var fixedToolbarAdded = false;
var fToolBar = null;
var EditorControlMap = Array();

window.status = '';
//Use this method to compare dates. The
//following variables can be used :  
//startDateFieldID, 
//startHourFieldID,
//startMinuteFieldID
//endDateFieldID -- Manditory,
//endHourFieldID, 
//endMinuteFieldID
function onResponseEnd(sender, arguments)
{
    var dt1 = new Date() 
    window.status = "Content saved at " + dt1.toLocaleTimeString();
};
function onRequestStart(sender, arguments)
{
    window.status = "Saving content...";
};
function textCounter(field, maxlimit)
{
    if (field.value.length > maxlimit)
    {
	    field.value = field.value.substring(0,maxlimit);
    }		
}
function AddZeros(number,requiredLength)
{
    number=number.toString();
    while (number.length<requiredLength)
    {
        number = "0" + number;
    }
    return number;
}
function fileDownload(applicationPath, fieldInstanceId,coState)
{
    var fileDownloadURL=applicationPath + "/admin/filedownload.aspx?fieldId=" + fieldInstanceId;
    fileDownloadURL=fileDownloadURL.replace("//","/");
	if (coState!=undefined)
	    fileDownloadURL=fileDownloadURL+"&coState=" + coState;	    
	window.open(fileDownloadURL,"workflowpopup","directories=no,height=100,width=100,location=no,menubar=no,resizable=yes,status=no,titlebar=no,toolbar=no,scrollbars=no");
} 

/*
function datesValidation(source, clientside_arguments)
{
    var startDate = new Date("yyyy mm dd");
    var endDate = new Date("yyyy mm dd");
    var startHour;
    var startMinute;
    var endHour;
    var endMinute;    
    //StartDate
    if (typeof startDateFieldID!="undefined")
    {
        var startDateField=document.getElementById(startDateFieldID + "_dateInput_text");
        startDate = startDateField.value;
    }
    else
        startDate = (new Date()).getFullYear() + "/" + AddZeros(((new Date()).getMonth()+1),2) + "/" + AddZeros((new Date()).getDate(),2);
    //EndDate 
    var endDateField=document.getElementById(endDateFieldID + "_dateInput_text");       
    endDate= endDateField.value;
    //StartHour
    if (typeof startHourFieldID!="undefined")
    {
        var startHourField=document.getElementById(startHourFieldID);
        startHour=startHourField.item(startHourField.selectedIndex).text;
    }
    else
        startHour="00";
    //StartMinute
    if (typeof startMinuteFieldID!="undefined")
    {
        var startMinuteField=document.getElementById(startMinuteFieldID); 
        startMinute=startMinuteField.item(startMinuteField.selectedIndex).text;
    }
    else
        startMinute="00";
    //EndHour
    if (typeof endHourFieldID!="undefined")
    {
        var endHourField=document.getElementById(endHourFieldID);
        endHour=endHourField.item(endHourField.selectedIndex).text;
    }
    else
        endHour="00";
    //EndMinute
    if (typeof endMinuteFieldID!="undefined")
    {
        var endMinuteField=document.getElementById(endMinuteFieldID);
        endMinute=endMinuteField.item(endMinuteField.selectedIndex).text;
    }
    else
        endMinute="00";
    
    
    var startDateTime = new Date("yyyy mm dd hh:mm:ss") 
    var endDateTime = new Date("yyyy mm dd hh:mm:ss") 
    
    startDateTime=startDateTime.getDate(startDate.toString() + " " + startHour + ":" + startMinute+":00");
                    
    endDateTime=endDateTime.getDate(endDate.toString() + " " + endHour + ":" + endMinute+":00");
    alert(startDateTime.getYear() + "\n" +
            startDateTime.getMonth() + "\n" +
            startDateTime.getDate());
    
    if (endDateTime<startDateTime)  
    {
        endDateField.focus();
        clientside_arguments.IsValid=false;                    
    }
    else
    {
        clientside_arguments.IsValid=true;    
    }
}
*/

function datesValidation(source, clientside_arguments)
{
    var startDate;
    var endDate;
    var startHour;
    var startMinute;
    var endHour;
    var endMinute;   
    var monthNames = ['January','February','March','April','May','June','July',
'August','September','October','November','December'];
 
    //StartDate
    if (typeof startDateFieldID!="undefined")
    {
        var startDateField=document.getElementById(startDateFieldID + "_dateInput_text");
        startDate = startDateField.value;
    }
    else
        startDate =  ((new Date()).getDate() + " " + monthNames[(new Date()).getMonth()] + " " + (new Date()).getYear()) //(new Date()).getFullYear() + "/" + AddZeros(((new Date()).getMonth()+1),2) + "/" + AddZeros((new Date()).getDate(),2);
    //EndDate 
    var endDateField=document.getElementById(endDateFieldID + "_dateInput_text");       
    endDate= endDateField.value;
    //StartHour
    if (typeof startHourFieldID!="undefined")
    {
        var startHourField=document.getElementById(startHourFieldID);
        startHour=startHourField.item(startHourField.selectedIndex).text;
    }
    else
        startHour="00";
    //StartMinute
    if (typeof startMinuteFieldID!="undefined")
    {
        var startMinuteField=document.getElementById(startMinuteFieldID); 
        startMinute=startMinuteField.item(startMinuteField.selectedIndex).text;
    }
    else
        startMinute="00";
    //EndHour
    if (typeof endHourFieldID!="undefined")
    {
        var endHourField=document.getElementById(endHourFieldID);
        endHour=endHourField.item(endHourField.selectedIndex).text;
    }
    else
        endHour="00";
    //EndMinute
    if (typeof endMinuteFieldID!="undefined")
    {
        var endMinuteField=document.getElementById(endMinuteFieldID);
        endMinute=endMinuteField.item(endMinuteField.selectedIndex).text;
    }
    else
        endMinute="00";
    
    
    var startDateTime;
    var endDateTime;
    
    startDateTime=new Date(startDate + " " + startHour + ":" + startMinute+":00");
                    
    endDateTime=new Date(endDate + " " + endHour + ":" + endMinute+":00");
    if (endDateTime<startDateTime)  
    {
        endDateField.focus();
        clientside_arguments.IsValid=false;                    
    }
    else
    {
        clientside_arguments.IsValid=true;    
    }
}

//Specifically for checking Live/Archive dates
function workflowDatesValidation(source, clientside_arguments)
{
    
    var startDate = new Date("yyyy mm dd");
    var endDate = new Date("yyyy mm dd");
    var startHour;
    var startMinute;
    var endHour;
    var endMinute;    
    if (typeof workflowNeverArchiveFieldID!="undefined")
    {
        var workflowNeverArchiveField=document.getElementById(workflowNeverArchiveFieldID);
        if (workflowNeverArchiveField.checked)
        {
            clientside_arguments.IsValid=true;
            return;
        }
    }
    
    //StartDate
    if (typeof workflowStartDateFieldID!="undefined")
    {
        var startDateField=document.getElementById(workflowStartDateFieldID + "_dateInput_text");
        startDate = startDateField.value;
    }
    else
        startDate = (new Date()).getFullYear() + "/" + ((new Date()).getMonth()+1) + "/" + (new Date()).getDate();
    //EndDate 
    var endDateField;
    if (typeof workflowEndDateFieldID!="undefined")
    {
        endDateField=document.getElementById(workflowEndDateFieldID + "_dateInput_text");       
        endDate= endDateField.value;
    }
    else
    {
        clientside_arguments.IsValid=true;
        return;   
    }
    //StartHour
    if (typeof workflowStartHourFieldID!="undefined")
    {
        var startHourField=document.getElementById(workflowStartHourFieldID);
        startHour=startHourField.item(startHourField.selectedIndex).text;
    }
    else
        startHour="00";
    //StartMinute
    if (typeof workflowStartMinuteFieldID!="undefined")
    {
        var startMinuteField=document.getElementById(workflowStartMinuteFieldID); 
        startMinute=startMinuteField.item(startMinuteField.selectedIndex).text;
    }
    else
        startMinute="00";
    //EndHour
    if (typeof workflowEndHourFieldID!="undefined")
    {
        var endHourField=document.getElementById(workflowEndHourFieldID);
        endHour=endHourField.item(endHourField.selectedIndex).text;
    }
    else
        endHour="00";
    //EndMinute
    if (typeof workflowEndMinuteFieldID!="undefined")
    {
        var endMinuteField=document.getElementById(workflowEndMinuteFieldID);
        endMinute=endMinuteField.item(endMinuteField.selectedIndex).text;
    }
    else
        endMinute="00";
    
    
    //var startDateTime = new Date("yyyy mm dd hh:mm:ss") 
    //var endDateTime = new Date("yyyy mm dd hh:mm:ss") 
    
    var startDateTime = new Date(startDate.toString() + " " + startHour + ":" + startMinute+":00");
                    
    var endDateTime =   new Date(endDate.toString() + " " + endHour + ":" + endMinute+":00");
    
    
    if (endDateTime<startDateTime)  
    {
        endDateField.focus();
        clientside_arguments.IsValid=false;                    
    }
    else
    {
        clientside_arguments.IsValid=true;    
    }
}


//Use this method to debug an object's properties
function debug(obj,root)
{
    var debugString="";
    var counter=0;
    var lines=0;
    var charIndex=0;
    for (property in obj)
    {
       
        debugString += root+"."+property + "=" + obj[property] + "\n";
        counter++;
        while (debugString.indexOf("\n",charIndex)>-1)
        {
           lines++;
           charIndex= debugString.indexOf("\n",charIndex)+1;
        }
        if (lines>20)
        {
            alert(debugString);
            counter=0;
            debugString="";
        }
        lines=0;
        charIndex=0;
    }
    alert(debugString);
}


/* This function needs to be called with a small delay after the page loads, to make sure that the fixed toolbar placeholder is created */
function MoveFixedToolbar()
{
    //alert(fToolBar);
    if(fToolBar == null)
    {
        //Get reference to any of the editor objects on the page.
        var editor = radEditor.Id;   

        //Get a reference to the Fixed placeholder object and move it to its new location
        //var fixedToolbar1 = document.getElementById("RadEditorRelativeToolbarHolder"); 
        fToolBar =  document.getElementById("RadEditorRelativeToolbarHolder"); 
        //alert(fToolBar);
        //fToolBar.className = "";
        if(fToolBar.parentNode.Id != "div_toolbar")
        {
            fToolBar.parentNode.removeChild(fToolBar); 
            fixedToolbarAdded = true;
            var newPlaceholder = document.getElementById("div_toolbar");
            newPlaceholder.appendChild(fToolBar);
        }
    }
      
    //window.setTimeout(focusEditor, 300); 
    //alert(newPlaceholder.innerHTML);      
 }
  
function focusEditor()
{
    window.focus();
    radEditor.SetFocus();
    radEditorDock.Show();
    radEditorDock.Hide();
    radEditorDock.Show();    
}
 
var divHid;
var radEditId;
var timerToolbar;

function cancelEditor()
{
    return OnClientCancel(radEditor);
}

function setEditorVisible(divEditorId, divContentId, divOriginalContentId, editorId, callbackId, pencilId)
{
        radCallbackId = callbackId;
        radEditor = GetRadEditor(editorId);
        var cArea = radEditor.GetContentArea();
        var dddd = document.getElementById(radEditor.Id.replace('editor1','divContent'));
        var topBar = document.getElementById(radEditor.Id.replace('ctl001','Topctl00'));
        var actualContent = document.getElementById(radEditor.Id.replace('ctl001','RadEContentHolderctl00'));
        ToggleVisibility(topBar);
        radEditor.SetSize(dddd.offsetWidth, dddd.offsetHeight + 55);
        //divEditor = divEditorId;
        //divEditorContent = divContentId;
        var divOriginalContent = document.getElementById(divOriginalContentId)
        divOriginalContent.value = radEditor.GetHtml();
       
        divOriginalContent.style.display="none";
        ShowHideObjects(divEditorId, divContentId);
         
        //actualContent.focus();
        
        divHid = document.createElement('div');
        divHid.Id = "divHid";
        divHid.innerHTML = "aaa";
        document.getElementById('dHid').appendChild(divHid); 
        document.getElementById(pencilId).style.display="none";
       
        window.setTimeout("focusEditor()", 50)
}

function focusEditor()
{
    radEditor.SetFocus();
}

function FindEditorControlMapIndex(editorId)
{
    var index=-1;
    for (var i=0;((i<EditorControlMap.length)&&(index==-1));i++)
    {
        if (EditorControlMap[i][0]==editorId)
        {
            index=i;
        }
    }
    return index;
}

function divEditorID(index) {return EditorControlMap[index][1];}
function divContentID(index) {return EditorControlMap[index][2];}
function divOriginalContentID(index) {return EditorControlMap[index][3];}
function editPenID(index) {return EditorControlMap[index][4];}

function OnClientCancel(editor)
{
    var ControlMapIndex=FindEditorControlMapIndex(editor.Id);
    var close = true;
    radEditor = GetRadEditor(editor.Id);
    divOriginalContent=document.getElementById(divOriginalContentID(ControlMapIndex));
    var originalData = divOriginalContent.value;//document.getElementById(divOriginalContentID(ControlMapIndex)).innerHTML;
    if(originalData != radEditor.GetHtml())
    {
        close &= confirm('You have unsaved changes. Click OK to lose these changes or Cancel to continue editing.');
    }
    if(close)
    {
        document.getElementById(editPenID(ControlMapIndex)).style.display = "block";
        if (isFullScreen)
        {
            radEditorScreen = GetRadEditor(editor.Id);
            radEditorScreen.Fire("ToggleScreenMode");
        }
        window.focus();
        ShowHideObjects(divContentID(ControlMapIndex), divEditorID(ControlMapIndex));        
        radEditor.SetHtml(divOriginalContent.value);
        radEditor = null;
        divEditor = null;
        //hide editor toolbar
        try
        {
            document.getElementById(divContentID(ControlMapIndex)).click();
        }
        catch(e){}
        divEditorContent = null;
        radCallbackId = null;
        originalData = null;
    }
    CheckinContent();
    return false;
}

function OnClientSubmit(editor)
{
    radEditor = null;
    divEditor = null;
    divEditorContent = null;
    radCallbackId = null;
    CheckinContent();
}
function resizeContentArea(editor)      
{         
    if (editor.InitialHeight == -1)      
    {      
        editor.InitialHeight = editor.Document.body.clientHeight;      
    }      
       
    var ie = document.all ? true : false;   
    var oDoc = editor.Document;       
    var targetHeight = ie? oDoc.body.scrollHeight : oDoc.documentElement.scrollHeight;   

    if (targetHeight > editor.InitialHeight)      
    {      
        var theIFrame = document.getElementById("RadEContentIframe" + editor.Id);      
        theIFrame.style.height = parseInt(targetHeight) + "px";        
        if (!ie) editor.SetSize(editor.GetWidth(), targetHeight);//FireFox bug, TD does not decrease height   
        
    }      
}  

var theEditor;

function OnClientLoad(editor)
{
    
    var iframe = document.getElementById(editor.Id);
    var newPlaceholder = document.getElementById("div_toolbar2");
    theEditor = editor;

    
    var theIFrame = document.getElementById("RadEContentIframe" + editor.Id);
    theIFrame.allowTransparency = true;
    
    var theMainEditorTable = document.getElementById("RadEWrapper" + editor.Id);

    var theParentEl = theMainEditorTable.parentNode.parentNode;
    var theContentArea = editor.GetContentArea();

    editor.AttachEventHandler ("onkeyup", 
        function (e)
        {
            setSizeAfterEdit(editor);
            
        }
    );
    editor.AttachEventHandler ("onkeydown", 
        function (e)
        {
            setSizeAfterEdit(editor);
        }
    );
    editor.AttachEventHandler("blur", function()
    {
        restorePoint = editor.CreateRestorePoint();            
    });
    
    var resizeFnRef = function anon(){setSizeAfterEdit(editor)};      
    editor.AttachEventHandler("RADEVENT_SEL_CHANGED", resizeFnRef)
    
    // This removes scrollbars
    
    for (var attr in theParentEl.currentStyle)
    {
        theContentArea.style[attr] = theParentEl.currentStyle[attr];
    }
        
  

    /*telerik code */ 
   
    editor.InitialHeight = -1;      
     
    editor.GetContentArea().style.overflow = "hidden";      
    editor.Document.body.scroll = "no";    
         
    var resizeFnRef = function anon(){resizeContentArea(editor)}; 
    //NdK - Commented out on 2008-04-25 to fix funny behaviour in editor     
    //editor.AttachEventHandler("RADEVENT_SEL_CHANGED", resizeFnRef);
    
    editor.AttachEventHandler("keydown", resizeFnRef)     
   
}
var timerPaste;
var radEditorPaste;
var restorePoint = null;
function OnClientCommandExecuted(editor, commandName, oTool)
{ 
    if ("InsertTable" == commandName)
	{ 
		//get a reference to the editor content area using the GetContentArea method
		var cArea = editor.GetContentArea();
		//get all TABLE elements in the content area
		var tables = cArea.getElementsByTagName("TABLE");
		for (var i=0; i < tables.length; i++)
		{
			var oTable = tables[i];
			//Check if this table existed before the InsertTable executed.
			if( !IsObjectInArray(oTable, curTables))
			{ 
				//set the table widht to 100%
				oTable.style.width = "100%"; 
			}
		} 
	}
	
	switch (commandName) 
	{
	
	     case 'Paste':
            {
                radEditorPaste = GetRadEditor(editor.Id);
                timerPaste = window.setInterval(setSizeAfterPaste, 500);
                break;
            }
        case 'PasteFromWord':
            {
                radEditorPaste = GetRadEditor(editor.Id);
                timerPaste = window.setInterval(setSizeAfterPaste, 500);
                break;
            }
        case 'PasteAsHtml':
            {
                radEditorPaste = GetRadEditor(editor.Id);
                timerPaste = window.setInterval(setSizeAfterPaste, 500);
                break;
            }
        case 'PastePlainText':
            {
                radEditorPaste = GetRadEditor(editor.Id);
                timerPaste = window.setInterval(setSizeAfterPaste, 500);
                break;
            }
        case 'Cut':
            {
                radEditorPaste = GetRadEditor(editor.Id);
                timerPaste = window.setInterval(setSizeAfterPaste, 500);
                break;
            }
        case 'ToggleScreenMode':
            {
                if (isFullScreen)
                    isFullScreen = false;
                else
                    isFullScreen = true;
            }
       case 'Undo':
            {
                radEditorPaste = GetRadEditor(editor.Id);
                timerPaste = window.setInterval(setSizeAfterPaste, 500);
                break;
            }  
       case 'Redo':
            {
                radEditorPaste = GetRadEditor(editor.Id);
                timerPaste = window.setInterval(setSizeAfterPaste, 500);
                break;
            }
            
    }
}
//-------------------------------------------------------------------------
function setSizeAfterPaste()
{
    divHid.innerHTML = radEditorPaste.GetHtml();
    
    if (!isFullScreen)
        radEditorPaste.SetSize(radEditorPaste.Width, divHid.offsetHeight + 60);
    
    window.clearInterval(timerPaste);
    divHid.innerHTML = "";
}
//-------------------------------------------------------------------------
function setSizeAfterEdit(editor)
{
    radEditor = GetRadEditor(editor.Id);
    if (divHid==null)//When the page first loads, then then divHid does not exist yet.
    {
        return
    }
    divHid.innerHTML = radEditor.GetHtml();
    
    if (!isFullScreen)
        radEditor.SetSize(radEditor.Width, divHid.offsetHeight + 60);
    divHid.innerHTML = "";
}
//-------------------------------------------------------------------------
function ToggleVisibility(fieldId)
{
    try
    {
	    if(document.getElementById(fieldId))
	    {
	        document.getElementById(fieldId).style.display = 
	            document.getElementById(fieldId).style.display == "block" ? "none" : "block";
	    }
    }
    catch(error)
    {
	    if(document.getElementById(fieldId))
	    {
	        document.getElementById(fieldId).style.display = 
	            document.getElementById(fieldId).style.display == "block" ? "none" : "block";
        }
    }
}
//show and hide objects by ID
function ShowHideObjects(fieldShow, fieldHide) 
{ 
    try
    {
	    if(document.getElementById(fieldShow))
	        {document.getElementById(fieldShow).style.display = "block";}
	    if(document.getElementById(fieldHide))
	        {document.getElementById(fieldHide).style.display = "none";}
    }
    catch(error)
    {
	    if(document.getElementById(fieldShow))
	        {document.getElementById(fieldShow).style.display = "block";}
	    if(document.getElementById(fieldHide))
	        {document.getElementById(fieldHide).style.display = "none";}
    }    
} 

function launchWin(url, w, h)
{
    return launchWin(url, w, h, "RadWindow1");
}
function launchWin(url, w, h, windowName)
{   
    windowName = windowName + "";
    if (windowName == "undefined")
        windowName = "RadWindow1";
        
    var oManager = GetRadWindowManager();
    var oWnd = oManager.GetWindowByName(windowName);
    oWnd.SetSize(w,h);
    oWnd.SetUrl(url);
    oWnd.Show();
    oManager = null;
    oWnd = null;
    return false;
}   
function launchRadWindow(url, w, h, windowName, windowTitle)
{   
    windowName = windowName + "";
    if (windowName == "undefined")
        windowName = "RadWindow1";
        
    if (windowTitle == "undefined")
        windowTitle = "Page Properties";
        
    var oManager = GetRadWindowManager();
    var oWnd = oManager.GetWindowByName(windowName);
    oWnd.SetSize(w,h);
    oWnd.SetTitle(windowTitle);
    oWnd.SetUrl(url);
    oWnd.Show();
    oManager = null;
    oWnd = null;
    return false;
}   

function scrollableWindowOpen(url,width,height)
{	
	var winl = (screen.width - width) / 2;
    var wint = (screen.height - height) / 2;
    window.open(url, '_blank', 'directories=no, fullscreen=no, height=' + height + ', width=' + width + ', location=no, menubar=no, resizable=no, scrollbars=yes, status=no, titlebar=no, toolbar=no, top=' + wint + ', left=' + winl + '', 'bReplace=false');
}	
function clickButton(e, buttonid)
{ 
    var bt = document.getElementById(buttonid); 
    if (typeof bt == 'object')
    {	
        if (is_ie)
        {       
            if (event.keyCode == 13)
            {	
                bt.click(); 
                return false; 
            }   
        }       
        if(is_nav)
        {	    
            if (e.keyCode == 13)
            {   
                bt.click(); 
                return false; 
            }   
        }       
    }           
}  
//function to add events to be fired when a page loads
function addLoadEvent(func) 
{
    var oldonload = window.onload;
    if (typeof window.onload != 'function') 
    {
        window.onload = func;
    } 
    else 
    {
        window.onload = function() 
        {
            if (oldonload) 
            {
                oldonload();
            }
            func();
        }
    }
}

function AddAltTagToFileInput(radUpload, arg)
{
    try
    {
        var file = GetFile(arg.FileInputField.value);
        arg.FileInputField.alt = file;
        arg.FileInputField.title = file;
    }
    catch(err){}
}
function GetFile(obj)
{
    var filePath;
    var filePathArray;
    var file;
    filePath=obj;
    filePathArray=filePath.split("\\");
    file=filePathArray[filePathArray.length-1]; 
    return file;
}
function ValidateRadioButtons(validator, args)  
{
    var txtValidate = document.getElementById(validator.targetcontrol);  
    if (txtValidate.value.length==0)
    {
        args.IsValid = false;   
        var radio = document.getElementById(validator.focuscontrol);  
        radio.focus();
    }
    else
    {
        args.IsValid = true;         
    }
}
function ValidateManditoryUpload(validator, args)  
{
    var radUpload = GetRadUpload(validator.attributes["targetcontrol"].nodeValue);   
    var fileInputs = radUpload.GetFileInputs();   
    var emptyFieldFlag = false;
    for(var i = 0; i < fileInputs.length; i++)   
    {   
        //If at least one empty input field exists   
        //the emptyFieldFlag is being raised   
        if(fileInputs[i].value.length == 0)   
        {   
            emptyFieldFlag = true;
            fileInputs[i].focus();    
            break;     
        }   
    }   
    //Checks whether there is an empty field   
    if(emptyFieldFlag)   
    {   
        args.IsValid = false;   
        //radUpload.focus();
    }   
    else args.IsValid = true;   
}
function ValidateFileExtention(source, arguments)
{
    var radUpload = GetRadUpload(source.attributes["targetcontrol"].nodeValue); 
    arguments.IsValid = radUpload.ValidateExtensions();
}