/**
 * This file contains functions used in multiple files which needs to declare global
 *
 * @author Interface
 * @created 10-20-2009
 * @version 1.0
 * 		
 */


/*
 * setCssClassName - Used to change css of gived element
 */
function setCssClassName(id, className) {
	if(id) {
   	 	document.getElementById(id).className = className;
    }
}


/*
 * openTermsOfUsePopupWindow - Open Terms Of Use Window 
 */
function openTermsOfUsePopupWindow(URL) {
	var openTermsOfUsePopupWindow = new Ext.Window({
		title: custom_labels.TermsOfUse_windowTitle,
	    id: 'openTermsOfUsePopupWindow',
  		width: 700,
  		height: 550,
	    resizable: false,
	    modal: true,
		hideParent: true,
    	border: false,
    	closable: true,
    	items: [{
			xtype: "panel",
			id: 'open-terms-of-use-panel',
			width: '100%',
			height: 540
		}]
	});
	
	openTermsOfUsePopupWindow.show();
}

/*
 * parseXMLResult : - used to parse the xml response
 */
function parseXMLResult(responseXML){
	//read status node from response xml
	var statusNode = Ext.DomQuery.selectNode('Status', responseXML);
	if (statusNode){
		//get value for status node
		var statusNodeValue = Ext.DomQuery.selectValue('Status', responseXML);
		if(statusNodeValue == lookup_codes.LOGIN_SUCCESS){
			return true;
		}else{
			var level = Ext.DomQuery.selectValue('Level', responseXML);
			if(level == lookup_codes.ERROR_APPLICATION_ERROR){
				// for level 1
				if(!Ext.getCmp('error-dialog-popup')){
					var errorDialog = new Ron.ErrorDialog({
			  			errorResponse: responseXML
			  		});
			  		errorDialog.show();
				}
		  			
			} else if(level == lookup_codes.ERROR_SESSION_EXPIRED){
				stopICCheckTimerFunction();
				// for level 2
				var errorCode = Ext.DomQuery.selectValue('Code', responseXML);
				if(errorCode.toUpperCase() == lookup_codes.SESSION_EXPIRED_ERROR_CODE){
					Ext.Msg.show({
				   		title:'Message',
				   		msg: custom_labels.APPSession_timeoutMessage,
				   		buttons: Ext.Msg.OK,
				   		closable: false,
				   		fn: redirectToLogin
					});
				} else if(errorCode.toUpperCase() == lookup_codes.USER_OLD_SESSION_EXPIRED_ERROR_CODE){
					Ext.Msg.show({
				   		title:'Message',
				   		msg: custom_labels.User_old_session_timeoutMessage,
				   		buttons: Ext.Msg.OK,
				   		closable: false,
				   		fn: redirectToLogin
					});
				}
			} else {
				// for level 3
				var errorCode = Ext.DomQuery.selectValue('Code', responseXML);
				Ext.Msg.alert( 'Message', custom_labels.ht.get(errorCode));
			}
		}
	}else {
		return false;
	}
}

/*
 * redirectToLogin : - function which redirects to login page after session expired
 */
function redirectToLogin(){
	if(userPrincipal.accountId){
		document.location.href = custom_labels.LOGIN_URL + '?AccountID=' + userPrincipal.accountId;
	}else {
		document.location.href = custom_labels.LOGIN_URL;	
	}	
}

/*
 * getQueryString : - retrivew query string value from url
 */
function getQueryString(key, default_) {
   	if (default_ == null) {
   		default_ = "";
   	}
  	key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  	var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  	var qs = regex.exec(window.location.href);
  	if(qs == null)
    	return default_;
  	else
    	return qs[1];
}

/*
 * openExtPopupWindow : - use to open a popup window
 
function openExtPopupWindow(URL, wWidth, wHeight, iType, id, name) {
	var openExtPopupWindow = new Ext.Window({
		title: name,
	    id: id,
  		width: wWidth,
  		height: wHeight,
	    resizable: false,
	    modal: true,
		hideParent: true,
    	border: false,
    	closable: true,    	
    	items: [{
			xtype: iType,
			width: '100%',
			height: 540
		}]
	});
	
	openExtPopupWindow.show();
}
*/

//Function to open popup window
var standardIntakeWin;
var winUrl;
window.name = "STANDARDINTAKE";
function openPopupWindow(URL, width, height) {			
	// if already open, use it
	if (standardIntakeWin != null && !standardIntakeWin.closed) {
		if(winUrl == URL){
			standardIntakeWin.focus();
			return;
		} else {
			standardIntakeWin.close();
		}				
	}
	// check if parent window exits. if yes, use it
	if (window.opener != null && !window.opener.closed) {
		window.opener.focus();
		return;
	}
	// open a new window
	standardIntakeWin = window.open(URL,'','resizable=yes,width='+width+', height='+height+',scrollbars=yes');
	winUrl = URL;
	if (standardIntakeWin != null && standardIntakeWin.opener == null) { 
		standardIntakeWin.opener = self;
		standardIntakeWin.focus();		
	}
	
	return standardIntakeWin;
}


//Function to open new popup window on every call
function openNewPopupWindow(URL, width, height) {
	// open a new window
	standardIntakeWin = window.open(URL);	
	return standardIntakeWin;
}

/*
 * Function to open new popup browser window for viewing image in Atalasoft viewer.
 */
function openViewerPopupWindow(URL) {
//	// if already open, use it
//	if (standardIntakeWin != null && !standardIntakeWin.closed) {
//		if(winUrl == URL){
//			standardIntakeWin.focus();
//			return;
//		} else {
//			standardIntakeWin.close();
//		}				
//	}
	// open a new window
	return window.open(URL,'','status=yes,location=0,fullscreen=yes,resizable=yes,scrollbars=no');
}

// FORM XML READER
Ext.form.XmlErrorReader = function(){
    Ext.form.XmlErrorReader.superclass.constructor.call(this, {
            record : 'Result',
            success: 'Status'
        }, [
            'id', 'msg'
        ]
    );
};
Ext.extend(Ext.form.XmlErrorReader, Ext.data.XmlReader);

/*
 * showSlidingMessageBox - This function is used to display sliding message
 * Use it as following
 * showSlidingMessageBox.msg('Message', 'Message here.');
 */
showSlidingMessageBox = function(){
    var msgCt;
    function createBox(t, s){
        return ['<div class="sliding-msg">',
                '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>',
                '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc">', s, '</div></div></div>',
                '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>',
                '</div>'].join('');
    }
    return {
        msg : function(title, format){
            if(!msgCt){
                msgCt = Ext.DomHelper.insertFirst(document.body, {id:'sliding-msg-div'}, true);
            }
            msgCt.alignTo('card-tabs-panel', 'r-tr');
            var s = String.format.apply(String, Array.prototype.slice.call(arguments, 1));
            var m = Ext.DomHelper.append(msgCt, {html:createBox(title, s)}, true);
            m.slideIn('t').pause(3).ghost("t", {remove:true});
        },

        init : function(){
            var lb = Ext.get('lib-bar');
            if(lb){
                lb.show();
            }
        }
    };
}();

/**
 * fileToValidate : - used to file validation
 * @param {} fileName
 */
function fileToValidate(fileName){	
	var extensions = lookup_codes.UPLOAD_SUPPORTED_FILE_EXTENSION_TYPE;
	var validExtensions = extensions.split(',');
	var type = fileName.slice(fileName.indexOf("\\") + 1);
    var extension = fileName.slice(fileName.lastIndexOf(".")).toLowerCase();    
    var allowSubmit = false;
    //loop through our array of extensions
    for (var i = 0; i < validExtensions.length; i++) {
        //check to see if it's the proper extension
        if (validExtensions[i] == extension) { 
            //it's the proper extension
            allowSubmit = true;            
        }
    }
    if(!allowSubmit){
    	Ext.Msg.alert( 'Error', custom_labels.File_validationFileTypeMsg);
    }
    return allowSubmit;
}

/*
 * Function to check whether photo uploaded is correct or not by extension.
 */
function contactPhotoToValidate(photoName){	
	var extensions = lookup_codes.CONTACT_PHOTO_SUPPORTED_FILE_EXTENSION_TYPE;
	var validExtensions = extensions.split(',');
	var type = photoName.slice(photoName.indexOf("\\") + 1);
    var extension = photoName.slice(photoName.lastIndexOf(".")).toLowerCase();    
    var allowSubmit = false;
    //loop through our array of extensions
    for (var i = 0; i < validExtensions.length; i++) {
        //check to see if it's the proper extension
        if (validExtensions[i] == extension) { 
            //it's the proper extension
            allowSubmit = true;            
        }
    }
    if(!allowSubmit){
    	Ext.Msg.alert( 'Error', custom_labels.File_validationFileTypeMsg);
    }
    return allowSubmit;
}

/**
 * isValidEmail : - used to validate email return true if valid else false
 * @param {} email
 */
function isValidEmail(email) {
	var reg = /^(\w+)([\-+.][\w]+)*@(\w[\-\w]*\.){1,5}([A-Za-z]){2,6}$/;	
	return reg.test(email);	
}

/**
 * trimText : - used to trim
 * @param {} text
 * @param {} len
 * @return {}
 */
function trimText(text, len){
    if(text.length > len){
        return text.substr(0, len - 3) + '...';
    }
    return text;
}

/**
 * UTCStringToDate : - used to convert utc to local format date 
 * @param {} dtStr
 * @param {} format
 * @return {String}
 */
function UTCStringToDate(dtStr, format){
    var dt = Date.parseDate(dtStr, format);
    if (dt == undefined) return ''; // or whatever you want to do
    return dt.fromUTC();
}

/*
 * To check if admin tab is present in center card tabs panel
 * 
 */
function checkIfViewerAdminTab(){
	var isAdmintabPresent = false;
	if(Ext.getCmp('card-tabs-panel').find('isAdminTab','true').length == 0){
		isAdmintabPresent = false;
	} else {
		isAdmintabPresent = true
	}
	return isAdmintabPresent;
}

/*
 * Function to get viewer's admin toolbar
 
function getAdminViewerToolbar(ID, viewerFrameName){
	var annotationMenu = new Ext.menu.Menu({	//menu for various annotation types.
	        id: 'admin-annotation-menu',
	        items: [{
            	text: custom_labels.ImageViewerPanel_ellipseBtn,
            	tooltip: custom_labels.ImageViewerPanel_ellipseBtnTooltip,
            	id: 'viewer-tab-panel-admin-toolbar-ellipseBtn',
            	iconCls: 'icon-ellipse',
            	hidden: false,
            	handler: function(){
            		createAnnotation(this, viewerFrameName);
            	}
            },'-',{
            	text: custom_labels.ImageViewerPanel_highlightBtn,
            	tooltip: custom_labels.ImageViewerPanel_highlightBtnTooltip,
            	id: 'viewer-tab-panel-admin-toolbar-highlighterBtn',
            	iconCls: 'icon-highlighter',
            	hidden: false,
            	handler: function(){
            		createAnnotation(this, viewerFrameName);
            	}
            },'-',{
            	text: custom_labels.ImageViewerPanel_lineBtn,
            	tooltip: custom_labels.ImageViewerPanel_lineBtnTooltip,
            	id: 'viewer-tab-panel-admin-toolbar-lineBtn',
            	iconCls: 'icon-line',
            	hidden: false,
            	handler: function(){
            		createAnnotation(this, viewerFrameName);
            	}
            },'-',{
            	text: custom_labels.ImageViewerPanel_upArrowLineBtn,
            	tooltip: custom_labels.ImageViewerPanel_upArrowLineBtnTooltip,
            	id: 'viewer-tab-panel-admin-toolbar-upArrowLineBtn',
            	iconCls: 'icon-upArrowLine',
            	hidden: false,
            	handler: function(){
            		createAnnotation(this, viewerFrameName);
            	}
            },'-',{
            	text: custom_labels.ImageViewerPanel_downArrowLineBtn,
            	tooltip: custom_labels.ImageViewerPanel_downArrowLineBtnTooltip,
            	id: 'viewer-tab-panel-admin-toolbar-downArrowLineBtn',
            	iconCls: 'icon-downArrowLine',
            	hidden: false,
            	handler: function(){
            		createAnnotation(this, viewerFrameName);
            	}
            },'-',{
            	text: custom_labels.ImageViewerPanel_freeHandBtn,
            	tooltip: custom_labels.ImageViewerPanel_freeHandBtnTooltip,
            	id: 'viewer-tab-panel-admin-toolbar-freeHandBtn',
            	iconCls: 'icon-freeHand',
            	hidden: false,
            	handler: function(){
            		createAnnotation(this, viewerFrameName);
            	}
            },'-',{
            	text: custom_labels.ImageViewerPanel_polygonBtn,
            	tooltip: custom_labels.ImageViewerPanel_polygonBtnTooltip,
            	id: 'viewer-tab-panel-admin-toolbar-polygonBtn',
            	iconCls: 'icon-polygon',
            	hidden: false,
            	handler: function(){
            		createAnnotation(this, viewerFrameName);
            	}
            },'-',{
            	text: custom_labels.ImageViewerPanel_rectangleBtn,
            	tooltip: custom_labels.ImageViewerPanel_rectangleBtnTooltip,
            	id: 'viewer-tab-panel-admin-toolbar-rectangleBtn',
            	iconCls: 'icon-rectangle',
            	hidden: false,
            	handler: function(){
            		createAnnotation(this, viewerFrameName);
            	}
            },'-',{
            	text: custom_labels.ImageViewerPanel_redactionBtn,
            	tooltip: custom_labels.ImageViewerPanel_redactionBtnTooltip,
            	id: 'viewer-tab-panel-admin-toolbar-redactionBtn',
            	iconCls: 'icon-redact',
            	hidden: false,
            	handler: function(){
            		createAnnotation(this, viewerFrameName);
            	}
            },'-',{
            	text: custom_labels.ImageViewerPanel_stickyNoteBtn,
            	tooltip: custom_labels.ImageViewerPanel_stickyNoteBtnTooltip,
            	id: 'viewer-tab-panel-admin-toolbar-stickyNoteBtn',
            	iconCls: 'icon-stickyNote',
            	hidden: false,
            	handler: function(){
            		createAnnotation(this, viewerFrameName);
            	}
            },'-',{
            	text: custom_labels.ImageViewerPanel_textAnnotationBtn,
            	tooltip: custom_labels.ImageViewerPanel_textAnnotationBtnTooltip,
            	id: 'viewer-tab-panel-admin-toolbar-textAnnotationBtn',
            	iconCls: 'icon-text',
            	hidden: false,
            	handler: function(){
            		createAnnotation(this, viewerFrameName);
            	}
            }]
    	});
    	
    	var cemmsMenu = new Ext.menu.Menu({	//menu for various CEMMS symbol annotation types.
	        id: 'admin-cemms-menu',
	        items: [{
            	text: custom_labels.ImageViewerPanel_assemblyAreaBtn,
            	tooltip: custom_labels.ImageViewerPanel_assemblyAreaBtnTooltip,
            	id: 'viewer-tab-panel-admin-toolbar-assemblyAreaBtn',
            	iconCls: 'icon-assemblyArea',
            	hidden: false,
            	handler: function(){
            		createAnnotation(this, viewerFrameName);
            	}
            },'-',{
            	text: custom_labels.ImageViewerPanel_assemblyArea1Btn,
            	tooltip: custom_labels.ImageViewerPanel_assemblyArea1BtnTooltip,
            	id: 'viewer-tab-panel-admin-toolbar-assemblyArea1Btn',
            	iconCls: 'icon-assemblyArea1',
            	hidden: false,
            	handler: function(){
            		createAnnotation(this, viewerFrameName);
            	}
            },'-',{
            	text: custom_labels.ImageViewerPanel_assemblyArea2Btn,
            	tooltip: custom_labels.ImageViewerPanel_assemblyArea2BtnTooltip,
            	id: 'viewer-tab-panel-admin-toolbar-assemblyArea2Btn',
            	iconCls: 'icon-assemblyArea2',
            	hidden: false,
            	handler: function(){
            		createAnnotation(this, viewerFrameName);
            	}
            },'-',{
            	text: custom_labels.ImageViewerPanel_assemblyArea3Btn,
            	tooltip: custom_labels.ImageViewerPanel_assemblyArea3BtnTooltip,
            	id: 'viewer-tab-panel-admin-toolbar-assemblyArea3Btn',
            	iconCls: 'icon-assemblyArea3',
            	hidden: false,
            	handler: function(){
            		createAnnotation(this, viewerFrameName);
            	}
            },'-',{
            	text: custom_labels.ImageViewerPanel_helibaseBtn,
            	tooltip: custom_labels.ImageViewerPanel_helibaseBtnTooltip,
            	id: 'viewer-tab-panel-admin-toolbar-helibaseBtn',
            	iconCls: 'icon-helibase',
            	hidden: false,
            	handler: function(){
            		createAnnotation(this, viewerFrameName);
            	}
            },'-',{
            	text: custom_labels.ImageViewerPanel_baseBtn,
            	tooltip: custom_labels.ImageViewerPanel_baseBtnTooltip,
            	id: 'viewer-tab-panel-admin-toolbar-baseBtn',
            	iconCls: 'icon-base',
            	hidden: false,
            	handler: function(){
            		createAnnotation(this, viewerFrameName);
            	}
            },'-',{
            	text: custom_labels.ImageViewerPanel_stagingAreaBtn,
            	tooltip: custom_labels.ImageViewerPanel_stagingAreaBtnTooltip,
            	id: 'viewer-tab-panel-admin-toolbar-stagingAreaBtn',
            	iconCls: 'icon-stagingArea',
            	hidden: false,
            	handler: function(){
            		createAnnotation(this, viewerFrameName);
            	}
            },'-',{
            	text: custom_labels.ImageViewerPanel_incidentCommandBtn,
            	tooltip: custom_labels.ImageViewerPanel_incidentCommandBtnTooltip,
            	id: 'viewer-tab-panel-admin-toolbar-incidentCommandBtn',
            	iconCls: 'icon-incidentCommand',
            	hidden: false,
            	handler: function(){
            		createAnnotation(this, viewerFrameName);
            	}
            },'-',{
            	text: custom_labels.ImageViewerPanel_chemicalsBtn,
            	tooltip: custom_labels.ImageViewerPanel_chemicalsBtnTooltip,
            	id: 'viewer-tab-panel-admin-toolbar-chemicalsBtn',
            	iconCls: 'icon-chemicals',
            	hidden: false,
            	handler: function(){
            		createAnnotation(this, viewerFrameName);
            	}
            },'-',{
            	text: custom_labels.ImageViewerPanel_electricalPanelBtn,
            	tooltip: custom_labels.ImageViewerPanel_electricalPanelBtnTooltip,
            	id: 'viewer-tab-panel-admin-toolbar-electricalPanelBtn',
            	iconCls: 'icon-electricalPanel',
            	hidden: false,
            	handler: function(){
            		createAnnotation(this, viewerFrameName);
            	}
            },'-',{
            	text: custom_labels.ImageViewerPanel_fireExtinguisherBtn,
            	tooltip: custom_labels.ImageViewerPanel_fireExtinguisherBtnTooltip,
            	id: 'viewer-tab-panel-admin-toolbar-fireExtinguisherBtn',
            	iconCls: 'icon-fireExtinguisher',
            	hidden: false,
            	handler: function(){
            		createAnnotation(this, viewerFrameName);
            	}
            },'-',{
            	text: custom_labels.ImageViewerPanel_exitBtn,
            	tooltip: custom_labels.ImageViewerPanel_exitBtnTooltip,
            	id: 'viewer-tab-panel-admin-toolbar-exitBtn',
            	iconCls: 'icon-exit',
            	hidden: false,
            	handler: function(){
            		createAnnotation(this, viewerFrameName);
            	}
            },'-',{
            	text: custom_labels.ImageViewerPanel_compassBtn,
            	tooltip: custom_labels.ImageViewerPanel_compassBtnTooltip,
            	id: 'viewer-tab-panel-admin-toolbar-compassBtn',
            	iconCls: 'icon-compass',
            	hidden: false,
            	handler: function(){
            		createAnnotation(this, viewerFrameName);
            	}
            }]
    	});
    	
    	var zoomMenu = new Ext.menu.Menu({	//menu for zoom. (Zoom In & Zoom Out).
	        id: 'admin-zoom-menu',
	        items: [{
            	text: custom_labels.ImageViewerPanel_zoomInBtn,
            	tooltip: custom_labels.ImageViewerPanel_zoomInTooltip,
            	id: 'viewer-tab-panel-admin-toolbar-zoomInBtn',
            	iconCls: 'icon-zoomIn',
            	handler: function(){
            		zoomInOut(this,'admin', viewerFrameName);
            	}
            },'-',{
            	text: custom_labels.ImageViewerPanel_zoomOutBtn,
            	tooltip: custom_labels.ImageViewerPanel_zoomOutTooltip,
            	id: 'viewer-tab-panel-admin-toolbar-zoomOutBtn',
            	iconCls: 'icon-zoomOut',
            	handler: function(){
            		zoomInOut(this,'admin', viewerFrameName);
            	}
            }]
    	});
    	
    	var tbViewerPanel = new Ext.Toolbar({
	    	id: ID + '-viewer-tab-panel-admin-toolbar',
	    	hidden: false,
	    	items: [{
	    		xtype: 'buttongroup',
	    		id: 'viewer-tab-panel-admin-toolbar-deleteSaveBtnGroup',
	            columns: 3,
	            border: false,
            	bodyBorder: false,
	            defaults: {
	            	scale: 'small'
	            },
	            items: [{
	                text: custom_labels.ImageViewerPanel_deleteAnnotBtn,
	                tooltip: custom_labels.ImageViewerPanel_deleteBtnTooltip,
	                id: 'viewer-tab-panel-admin-toolbar-deleteAnnotBtn',
	                iconCls: 'icon-delete',
	                handler: function(){
	            		deleteSaveAnnotations(this, viewerFrameName);
	            	}
	                
	            },{
	            	text: custom_labels.ImageViewerPanel_saveAnnotBtn,
	            	tooltip: custom_labels.ImageViewerPanel_saveBtnTooltip,
	            	id: 'viewer-tab-panel-admin-toolbar-saveAnnotBtn',
	                iconCls: 'icon-save',
	                handler: function(){
	            		deleteSaveAnnotations(this, viewerFrameName);
	            	}
	                
	            },{
	            	text: custom_labels.ImageViewerPanel_printBtn,
	            	tooltip: custom_labels.ImageViewerPanel_printBtnTooltip,
	            	id: 'viewer-tab-panel-admin-toolbar-printBtn',
	                iconCls: 'icon-print',
	                handler: function(){
	            		openPrintImageOptionPopup(this, viewerFrameName);
	            	}
	                
	            }]
	    	},{
	            xtype: 'buttongroup',
	            id: 'viewer-tab-panel-admin-toolbar-annotationMenu',
	            columns: 1,
	            defaults: {
	                scale: 'small'
	            },
	            items: [{
	                xtype:'splitbutton',
	                text: custom_labels.ImageViewerPanel_openAnnotationMenuBtn,
	                menu: annotationMenu,
	                tooltip: custom_labels.ImageViewerPanel_annotationOpenMenuTooltip
	            }]
	        },{
	            xtype: 'buttongroup',
	            columns: 2,
	            defaults: {
	                scale: 'small'
	            },
	            items: [{
	                xtype:'splitbutton',
	                text: 'Zoom',
	                iconCls: 'icon-zoom',
	                menu: zoomMenu
	            },{
	                text: custom_labels.ImageViewerPanel_panBtn,
	            	tooltip: custom_labels.ImageViewerPanel_panTooltip,
	            	id: 'viewer-tab-panel-admin-toolbar-panBtn',
	            	iconCls: 'icon-pan',
	            	handler: function(){
	            		zoomInOut(this,'admin', viewerFrameName);
	            	}
	            }]
        	},{
	            xtype: 'buttongroup',
	            id: 'viewer-tab-panel-admin-toolbar-cemmsMenu',
	            columns: 1,
	            defaults: {
	                scale: 'small'
	            },
	            items: [{
	                xtype:'splitbutton',
	                text: custom_labels.ImageViewerPanel_openCEMMSMenuBtn,
	                tooltip: custom_labels.ImageViewerPanel_cemmsOpenMenuTooltip,
	                menu: cemmsMenu
	            }]
	        },'->',{
            	text: custom_labels.ImageViewerPanel_openViewerInNewWindowBtn,
            	tooltip: custom_labels.ImageViewerPanel_openViewerInNewWindowTooltip,
            	id: 'viewer-tab-panel-admin-toolbar-openViewerInNewWindowBtn',
            	iconCls: 'icon-fullScreen',
            	handler: function(){
            		openFullScreenViewer(ID);
            	},
            	hidden: false
            }]
	    });
	    
	    return tbViewerPanel;
}
*/


/*
 * Function to get viewer's user toolbar
 */
function getUserViewerToolbar(ID, viewerFrameName,fileName, typeID, type, accountID, title, imageID){
		
	var tbViewerPanel = new Ext.Toolbar({
    	id: ID + '-viewer-tab-panel-user-toolbar',
    	hidden: false,
    	items: [{
            xtype: 'buttongroup',
            columns: 1,
            defaults: {
                scale: 'small'
            },
            items: [{
            	text: custom_labels.ImageViewerPanel_printBtn,
            	tooltip: custom_labels.ImageViewerPanel_printBtnTooltip,
            	id: 'viewer-tab-panel-user-toolbar-printBtn',
                iconCls: 'icon-print',
                handler: function(){
            		openPrintImageOptionPopup(this, viewerFrameName);
            	}
                
            }]
    	},{
            xtype: 'buttongroup',
            columns: 3,
            defaults: {
                scale: 'small'
            },
            items: [{
            	text: custom_labels.ImageViewerPanel_zoomInBtn,
            	tooltip: custom_labels.ImageViewerPanel_zoomInTooltip,
            	id: 'viewer-tab-panel-user-toolbar-zoomInBtn',
            	iconCls: 'icon-zoomIn',
            	handler: function(){
            		zoomInOut(this,'user', viewerFrameName);
            	}
            },{
            	text: custom_labels.ImageViewerPanel_zoomOutBtn,
            	tooltip: custom_labels.ImageViewerPanel_zoomOutTooltip,
            	id: 'viewer-tab-panel-user-toolbar-zoomOutBtn',
            	iconCls: 'icon-zoomOut',
            	handler: function(){
            		zoomInOut(this,'user', viewerFrameName);
            	}
            },{
                text: custom_labels.ImageViewerPanel_panBtn,
            	tooltip: custom_labels.ImageViewerPanel_panTooltip,
            	id: 'viewer-tab-panel-user-toolbar-panBtn',
            	iconCls: 'icon-pan',
            	handler: function(){
            		zoomInOut(this,'user', viewerFrameName);
            	}
            }]
    	},'->',{
        	text: custom_labels.ImageViewerPanel_openViewerInEditModeBtn_text,
        	tooltip: custom_labels.ImageViewerPanel_openViewerInEditModeBtn_tooltip,
        	id: 'viewer-tab-panel-user-toolbar-openViewerInEditModeBtn',
        	iconCls: 'icon-edit',
        	handler: function(){
        		openImageInEditMode(fileName, typeID, type, accountID, title, imageID);
//        		var requestParams = {};
//				requestParams.onAction = 'GET-VIEWER-ADMIN-TAB-STATUS';
//				requestParams.Feature = window.lookup_codes.ATALASOFT_VIEWER_FEATURE_VALUE;
//				requestParams.Action = window.lookup_codes.ATALASOFT_VIEWER_GET_STATUS_PARAM_ACTION_VALUE;
//				requestParams.fileName = fileName;
//				requestParams.typeID = typeID;
//				requestParams.type = type;
//				requestParams.accountID = accountID;
//				requestParams.title = title;
//				requestParams.imageID = imageID;
//				
//				// XHR call to get viewer admin tab status for this account
//				handleXHRCalls(custom_labels.HANDLER_URL, requestParams);
        	},
        	hidden: false
        },{
        	text: custom_labels.ImageViewerPanel_openViewerInNewWindowBtn,
        	tooltip: custom_labels.ImageViewerPanel_openViewerInNewWindowTooltip,
        	id: 'viewer-tab-panel-user-toolbar-openViewerInNewWindowBtn',
        	iconCls: 'icon-fullScreen',
        	handler: function(){
        		openFullScreenViewer(fileName, typeID, type, accountID, title, imageID)
        	},
        	hidden: false
        }]
    });
	    
	    return tbViewerPanel;
}

/*
 * Function to add/activate viewer tab
 */
function addViewerPanel(fileName, typeID, type, accountID, title, imageID, isViewerAdminTabOpen){

	var requestParams = {};
	requestParams.onAction = 'GET-VIEWER-IMAGE-DETAILS';
	requestParams.Feature = lookup_codes.ATALASOFT_VIEWER_FEATURE_VALUE;
	requestParams.Action = lookup_codes.ATALASOFT_VIEWER_IMAGE_VIEW_PARAM_ACTION_VALUE;
	requestParams.FileName = fileName;
	requestParams.TypeID = typeID;
	requestParams.Type = type;
	requestParams.accountID = accountID;
	requestParams.title = title;
	requestParams.imageID = imageID;
	
	// XHR call to get viewer admin tab status for this account
	handleXHRCalls(custom_labels.HANDLER_URL, requestParams);
	
	
}

/*
 * Function to call create annotation function in viewer aspx page
 */
function createAnnotation(button, viewerFrameName){
	if (window.frames[viewerFrameName]) {
    	if (button.id == Ext.getCmp('viewer-tab-panel-admin-toolbar-ellipseBtn').id) {
            if (window.frames[viewerFrameName].annotations) {
                window.frames[viewerFrameName].annotations('ellipse');
            }
        } else if (button.id == Ext.getCmp('viewer-tab-panel-admin-toolbar-highlighterBtn').id) {
            if (window.frames[viewerFrameName].annotations) {
                window.frames[viewerFrameName].annotations('highlighter');
            }
        } else if (button.id == Ext.getCmp('viewer-tab-panel-admin-toolbar-lineBtn').id) {
            if (window.frames[viewerFrameName].annotations) {
                window.frames[viewerFrameName].annotations('line');
            }
        }
        else if (button.id == Ext.getCmp('viewer-tab-panel-admin-toolbar-upArrowLineBtn').id) {
            if (window.frames[viewerFrameName].annotations) {
                window.frames[viewerFrameName].annotations('upArrowLine');
            }
        } else if (button.id == Ext.getCmp('viewer-tab-panel-admin-toolbar-downArrowLineBtn').id) {
            if (window.frames[viewerFrameName].annotations) {
                window.frames[viewerFrameName].annotations('downArrowLine');
            }
        }
        else if (button.id == Ext.getCmp('viewer-tab-panel-admin-toolbar-freeHandBtn').id) {
            if (window.frames[viewerFrameName].annotations) {
                window.frames[viewerFrameName].annotations('freeHand');
            }
        } else if (button.id == Ext.getCmp('viewer-tab-panel-admin-toolbar-polygonBtn').id) {
            if (window.frames[viewerFrameName].annotations) {
                window.frames[viewerFrameName].annotations('polygon');
            }
        } else if (button.id == Ext.getCmp('viewer-tab-panel-admin-toolbar-rectangleBtn').id) {
            if (window.frames[viewerFrameName].annotations) {
                window.frames[viewerFrameName].annotations('rectangle');
            }
        } else if (button.id == Ext.getCmp('viewer-tab-panel-admin-toolbar-redactionBtn').id) {
            if (window.frames[viewerFrameName].annotations) {
                window.frames[viewerFrameName].annotations('redaction');
            }
        } else if (button.id == Ext.getCmp('viewer-tab-panel-admin-toolbar-stickyNoteBtn').id) {
            if (window.frames[viewerFrameName].annotations) {
                window.frames[viewerFrameName].annotations('stickyNote');
            }
        } else if (button.id == Ext.getCmp('viewer-tab-panel-admin-toolbar-textAnnotationBtn').id) {
            if (window.frames[viewerFrameName].annotations) {
                window.frames[viewerFrameName].annotations('text');
            }
        } else if (button.id == Ext.getCmp('viewer-tab-panel-admin-toolbar-assemblyAreaBtn').id) {
            if (window.frames[viewerFrameName].annotations) {
                window.frames[viewerFrameName].annotations('assemblyArea');
            }
        } else if (button.id == Ext.getCmp('viewer-tab-panel-admin-toolbar-assemblyArea1Btn').id) {
            if (window.frames[viewerFrameName].annotations) {
                window.frames[viewerFrameName].annotations('assemblyArea1');
            }
        } else if (button.id == Ext.getCmp('viewer-tab-panel-admin-toolbar-assemblyArea2Btn').id) {
            if (window.frames[viewerFrameName].annotations) {
                window.frames[viewerFrameName].annotations('assemblyArea2');
            }
        } else if (button.id == Ext.getCmp('viewer-tab-panel-admin-toolbar-assemblyArea3Btn').id) {
            if (window.frames[viewerFrameName].annotations) {
                window.frames[viewerFrameName].annotations('assemblyArea3');
            }
        } else if (button.id == Ext.getCmp('viewer-tab-panel-admin-toolbar-helibaseBtn').id) {
            if (window.frames[viewerFrameName].annotations) {
                window.frames[viewerFrameName].annotations('helibase');
            }
        } else if (button.id == Ext.getCmp('viewer-tab-panel-admin-toolbar-baseBtn').id) {
            if (window.frames[viewerFrameName].annotations) {
                window.frames[viewerFrameName].annotations('base');
            }
        } else if (button.id == Ext.getCmp('viewer-tab-panel-admin-toolbar-stagingAreaBtn').id) {
            if (window.frames[viewerFrameName].annotations) {
                window.frames[viewerFrameName].annotations('stagingArea');
            }
        } else if (button.id == Ext.getCmp('viewer-tab-panel-admin-toolbar-incidentCommandBtn').id) {
            if (window.frames[viewerFrameName].annotations) {
                window.frames[viewerFrameName].annotations('incidentCommand');
            }
        } else if (button.id == Ext.getCmp('viewer-tab-panel-admin-toolbar-chemicalsBtn').id) {
            if (window.frames[viewerFrameName].annotations) {
                window.frames[viewerFrameName].annotations('chemicals');
            }
        } else if (button.id == Ext.getCmp('viewer-tab-panel-admin-toolbar-electricalPanelBtn').id) {
            if (window.frames[viewerFrameName].annotations) {
                window.frames[viewerFrameName].annotations('electricalPanel');
            }
        } else if (button.id == Ext.getCmp('viewer-tab-panel-admin-toolbar-fireExtinguisherBtn').id) {
            if (window.frames[viewerFrameName].annotations) {
                window.frames[viewerFrameName].annotations('fireExtinguisher');
            }
        } else if (button.id == Ext.getCmp('viewer-tab-panel-admin-toolbar-exitBtn').id) {
            if (window.frames[viewerFrameName].annotations) {
                window.frames[viewerFrameName].annotations('exit');
            }
        } else if (button.id == Ext.getCmp('viewer-tab-panel-admin-toolbar-compassBtn').id) {
            if (window.frames[viewerFrameName].annotations) {
                window.frames[viewerFrameName].annotations('compass');
            }
        }
	}
}

/*
 * Function to call zoom in/out/pan function in viewer aspx page
 */
function zoomInOut(button, roleType, viewerFrameName){
	if(roleType == 'admin'){
		if (window.frames[viewerFrameName]) {
	    	if (button.id == Ext.getCmp('viewer-tab-panel-admin-toolbar-zoomInBtn').id) {
	            if (window.frames[viewerFrameName].zoomIn) {
	                window.frames[viewerFrameName].zoomIn();
	            }
	        } else if (button.id == Ext.getCmp('viewer-tab-panel-admin-toolbar-zoomOutBtn').id) {
	            if (window.frames[viewerFrameName].zoomOut) {
	                window.frames[viewerFrameName].zoomOut();
	            }
	        } else if (button.id == Ext.getCmp('viewer-tab-panel-admin-toolbar-panBtn').id) {
	            if (window.frames[viewerFrameName].pan) {
	                window.frames[viewerFrameName].pan();
	            }
	        }
		} 
	} else if(roleType == 'user'){
		if (window.frames[viewerFrameName]) {
	    	if (button.id == Ext.getCmp('viewer-tab-panel-user-toolbar-zoomInBtn').id) {
	            if (window.frames[viewerFrameName].zoomIn) {
	                window.frames[viewerFrameName].zoomIn();
	            }
	        } else if (button.id == Ext.getCmp('viewer-tab-panel-user-toolbar-zoomOutBtn').id) {
	            if (window.frames[viewerFrameName].zoomOut) {
	                window.frames[viewerFrameName].zoomOut();
	            }
	        } else if (button.id == Ext.getCmp('viewer-tab-panel-user-toolbar-panBtn').id) {
	            if (window.frames[viewerFrameName].pan) {
	                window.frames[viewerFrameName].pan();
	            }
	        }
		}
	}
}

/*
 * Function to call delete/save annotation function in viewer aspx page
 */
function deleteSaveAnnotations(button, viewerFrameName){
	if (window.frames[viewerFrameName]) {
    	if (button.id == Ext.getCmp('viewer-tab-panel-admin-toolbar-deleteAnnotBtn').id) {
            if (window.frames[viewerFrameName].deleteSelectedAnnotations) {
                window.frames[viewerFrameName].deleteSelectedAnnotations();
            }
        } else if (button.id == Ext.getCmp('viewer-tab-panel-admin-toolbar-saveAnnotBtn').id) {
            if (window.frames[viewerFrameName].saveAnnotations) {
                window.frames[viewerFrameName].saveAnnotations();
            }
        }
	}
}

/*
 * Function to print image in viewer.
 */
function openPrintImageOptionPopup(button, viewerFrameName){
	
	var printImageOptionWindow = new Ext.Window({
		title: custom_labels.ImageViewerPanel_printImageOptionWindow_title,
	    id: 'print-image-option-popup-window',
  		width: 350,
  		height: 175,
	    resizable: false,
	    modal: true,
		hideParent: true,
    	border: false,
    	closable: true,
    	items:[{
    		id: 'print-image-option-popup-form-panel',
			layout: 'fit',
			border: false,
			items:{
				xtype: 'printimageoptionform',
				labels: custom_labels
			}
    	}],
    	buttons : [{
			 text : custom_labels.ImageViewerPanel_printImageOptionForm_nextBtn_text,
			id: 'print-image-option-form-nextBtn',
			handler: function(){
				var userChoice = 0;
				if(Ext.getCmp('print-image-optiom-form-without-annotations').getValue()){
					userChoice = 1;
				} else if(Ext.getCmp('print-image-optiom-form-with-annotations').getValue()){
					userChoice = 2;
				}
				printViewerImage(userChoice, viewerFrameName);
				
				Ext.getCmp('print-image-option-popup-window').close();
			}
		},{
			text : custom_labels.ImageViewerPanel_printImageOptionForm_cancelBtn_text,
			id: 'print-image-option-form-cancelBtn',
			handler: function(){
				Ext.getCmp('print-image-option-popup-window').close();
			}
		}]
	});
	
	printImageOptionWindow.show();
}

function printViewerImage(userChoice, viewerFrameName){
	if(userChoice > 0){
		if (window.frames[viewerFrameName]) {
			if (window.frames[viewerFrameName].printAtalasoftViewerImage) {
				window.frames[viewerFrameName].printAtalasoftViewerImage(userChoice);
			}
		}
	}
}

/*
 * Function to open image in full screen
 */
function openFullScreenViewer(fileName, typeID, type, accountID, title, imageID, imageUrl) {
		
	var ID = '';
	ID = imageID + '-' + typeID + '-' + type; 
	var viewerRequestParams = "?FName=" + fileName + 
								"&TypeID=" + typeID + 
								"&Type=" + type + 
								"&accountId=" + accountID + 
								"&Title=" + title + 
								"&ImageID=" + imageID +  
								"&ParentPanelID=" + ID + 
								"&isAdminToolbar=" + 'NO' +
								"&imageUrl=" + imageUrl;
  	var childWindowHandle = openViewerPopupWindow(custom_labels.FullScreenPage_URL + viewerRequestParams);
}

/*
 * Function to reload viewer
 */
function reloadViewer(isCloseAdminTab, requestParams) {
    if (isCloseAdminTab) {
        closeViewerAdminTab(requestParams);
    }
}

function closeViewerAdminTab(requestParams) {
    var handlerRequestParams = {};
    handlerRequestParams.onAction = 'CLOSE-VIEWER-ADMIN-TAB';
    handlerRequestParams.Feature = window.lookup_codes.ATALASOFT_VIEWER_FEATURE_VALUE;
    handlerRequestParams.Action = window.lookup_codes.ATALASOFT_VIEWER_CLOSE_VIEWER_PARAM_ACTION_VALUE;
    handlerRequestParams.FileName = requestParams.FileName;
    handlerRequestParams.TypeID = requestParams.TypeID;
    handlerRequestParams.Type = requestParams.Type;
    handlerRequestParams.accountID = requestParams.accountID;
    handlerRequestParams.title = requestParams.title;
    handlerRequestParams.imageID = requestParams.imageID;

    // XHR call to close viewer admin tab
    handleXHRCalls(custom_labels.HANDLER_URL, handlerRequestParams);
}

var viewerEditPopWindowHandle = null;
function openImageInEditMode(fileName, typeID, type, accountID, title, imageID){
	if(userPrincipal.getFeatures(lookup_codes.ATALASOFT_VIEWER_ID).getEdit() == lookup_codes.FEATURE_DISABLED){
		Ext.Msg.alert('Message', 'You are not authorized to open image in Edit mode.');
	} else {
		var ID = '';
		ID = imageID + '-' + typeID + '-' + type;
	
		var viewerRequestParams = '?FName=' + fileName + '&TypeID=' + typeID + '&Type=' + type + '&accountId=' + accountID + '&Title=' + title + '&ImageID=' + imageID + "&ParentPanelID=" + ID + "&isAdminToolbar=" + 'YES';
		
		viewerEditPopWindowHandle = openViewerPopupWindow(custom_labels.AtalasoftFullScreenPage_URL + viewerRequestParams);	
	}
}

/**
 * getAccountTypes - return account types array
 */
function getAccountTypes() {
	var accountTypes = [
		[1, 'School'],
        [2, 'OEM']
    ];
    return accountTypes;
}

function openImageInEditModeFromGrid(fileName,typeID,type,accountID,imageTitle,imageID){
	var requestParams = {};
	requestParams.onAction = 'GET-VIEWER-ADMIN-TAB-STATUS';
	requestParams.Feature = window.lookup_codes.ATALASOFT_VIEWER_FEATURE_VALUE;
	requestParams.Action = window.lookup_codes.ATALASOFT_VIEWER_GET_STATUS_PARAM_ACTION_VALUE;
	requestParams.fileName = fileName;
	requestParams.typeID = typeID;
	requestParams.type = type;
	requestParams.accountID = accountID;
	requestParams.title = imageTitle;
	requestParams.imageID = imageID;

	// XHR call to get viewer admin tab status for this account
	handleXHRCalls(custom_labels.HANDLER_URL, requestParams);
}



