function adminLogout(){
	window.location.href = base_url+admin_folder+'login/signout';
	return false;
}
function generateString(length){
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < length; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}

function stripTags(string){
	return string.replace(/(<([^>]+)>)/ig,"");
}

function hideField(field)
{
	field.disable();// for validation
	field.hide();
	field.getEl().up('.x-form-item').setDisplayed(false); // hide label
}

function showField(field)
{
	field.enable();
	field.show();
	field.getEl().up('.x-form-item').setDisplayed(true);// show label
}

function deleteOldAssets()
{
	Ext.Ajax.request({
		url: base_url+admin_url+'delete_old_assets' 
		,method: 'POST'
		,success: function(result,request){
			var jsonData = Ext.util.JSON.decode(result.responseText);
		}
		,failure: function(){}
		,headers: {'Powered-By': 'Ext'}
	});
	return false;
}

function deleteOldLabels()
{
	Ext.Ajax.request({
		url: base_url+admin_url+'delete_old_labels' 
		,method: 'POST'
		,success: function(result,request){
			var jsonData = Ext.util.JSON.decode(result.responseText);
		}
		,failure: function(){}
		,headers: {'Powered-By': 'Ext'}
	});
	return false;
}

function addRecord(grid,record)
{
	var store = grid.store;
	if(store.recordType) {
		var rec = new store.recordType(record);
		rec.commit();
		store.add(rec);
		return rec;
	}
	return false;
}

function deleteRecord(grid,record)
{
	Ext.Msg.show({
		title:'DELETE RECORD'
		,msg:'Are you sure you want to delete this record?'
		,icon:Ext.Msg.QUESTION
		,buttons:Ext.Msg.YESNO
		,scope:this
		,fn:function(response) {
			if('yes' !== response) {
				return;
			}
			grid.store.remove(record);
		}
	});
}

function addNode(tree,insertUrl,refreshUrl,params)
{
	root = tree.getRootNode();
	Ext.Ajax.request({
		url: insertUrl
		,params: params
		,method: 'POST'
		,success: function(result,request){
			var jsonData = Ext.util.JSON.decode(result.responseText);
			root.appendChild({
				id: jsonData.id
				,text: 'New Record - '+jsonData.id
				,leaf: false
			});
			refreshTree(tree,refreshUrl,false);
		}
		,failure: function(){}
		,headers: {'Powered-By': 'Ext'}
	});
	return false;
}

function cloneNode(tree,cloneUrl,refreshUrl)
{
	var node = tree.getSelectionModel().getSelectedNode();
	Ext.Ajax.request({
		url: cloneUrl
		,method: 'POST'
		,params: {id: node.id}
		,success: function(result,request){
			// refreshTree(tree,refreshUrl,true);
			refreshTree(tree,refreshUrl,false);
		}
		,failure: function(){}
		,headers: {'Powered-By': 'Ext'}
	});	
	return false;
}
	
function deleteNode(tree,deleteUrl,refreshUrl)
{
	var node = tree.getSelectionModel().getSelectedNode();
	Ext.Msg.show({
		title:'DELETE RECORD'
		,msg:'Are you sure you want to delete this record?'
		,icon:Ext.Msg.QUESTION
		,buttons:Ext.Msg.YESNO
		,scope:this
		,fn:function(response) {
			if('yes' === response) {
				Ext.Ajax.request({
					url: deleteUrl
					,method: 'POST'
					,params: {id: node.id}
					,success: function(result,request){
						node.remove();
						refreshTree(tree,refreshUrl,false);
					}
					,failure: function(){}
					,headers: {'Powered-By': 'Ext'}
				});	
			}
		}
	});
	return false;
}

function refreshTree(tree,url,expand){
	Ext.Ajax.request({
		url: url 
		,method: 'POST'
		,success: function(result,request){
			var jsonData = Ext.util.JSON.decode(result.responseText);
		}
		,failure: function(){}
		,headers: {'Powered-By': 'Ext'}
	});

	if(expand){
		root = tree.getRootNode();
		tree.getLoader().load(root);
		root.expand();	
	}
	return false;
}

function massDeleteFiles()
{
	var fileIds    = '';
	var grid       = Ext.getCmp("filesGrid");
	var selections = grid.getSelectionModel().getSelections();
	for(var i=0;i<selections.length;i++){		
		fileIds += (fileIds===''?'':',')+selections[i].data.file_id;		
	}

	Ext.Msg.show({
		title:'DELETE RECORD'
		,msg:'Are you sure you want to delete these files?'
		,icon:Ext.Msg.QUESTION
		,buttons:Ext.Msg.YESNO
		,scope:this
		,fn:function(response) {
			if('yes' !== response) {
				return;
			}
			Ext.Ajax.request({
				url: base_url+admin_folder+'files/mass_delete'
				,params:{
					file_ids: fileIds
				}
				,method: 'POST'
				,success: function(){
					grid.store.reload();
				}
				,failure: function(){}
				,headers: {
					'Powered-By': 'Ext'
				}
			});
		}
	});	
	return true;
}

function deleteFile(grid,fileId)
{
	Ext.Msg.show({
		title:'DELETE RECORD'
		,msg:'Are you sure you want to delete this record?'
		,icon:Ext.Msg.QUESTION
		,buttons:Ext.Msg.YESNO
		,scope:this
		,fn:function(response) {
			if('yes' !== response) {
				return;
			}
			Ext.Ajax.request({
				url: base_url+admin_folder+'files/delete'
				,params:{
					file_id: fileId
				}
				,method: 'POST'
				,success: function(){
					grid.store.reload();
				}
				,failure: function(){}
				,headers: {
					'Powered-By': 'Ext'
				}
			});
			return;
		}
	});	
}

function addCKEditor(form,editorId,fieldLabel,fieldName)
{
	form.add({
		xtype: 'ckeditor'
		,id: editorId
		,fieldLabel: fieldLabel
		,name: fieldName
		,CKConfig: {
			customConfig : base_url+'assets/ckeditor/config.js'
			,toolbar: 'Basic'
			,contentsCss: base_url+'assets/ckeditor/ck.css'
		}
		,listeners: {
			render: function(){
				new Ext.dd.DropTarget(Ext.get('x-form-el-'+editorId), {ddGroup:'group1',
					notifyDrop: function(dd, e, data) {
						for(var e=0;e<data.nodes.length;e++){
							if(data.nodes[e].title==1){
								var src = base_url+"assets/uploads/"+data.nodes[e].id;
								Ext.getCmp(editorId).insertHtml("<img src='"+src+"' />");
							} else {
								var href = base_url+"assets/uploads/"+data.nodes[e].id;
								Ext.getCmp(editorId).insertHtml("<a href='"+href+"'>"+data.nodes[e].id+"<a/>");
							}
						}
						return true;
					}
				});
			}
		}
	});
	return false;
}

function createDataViewPanel(isImage)
{
	var baseParams = {
		start: 0
		,limit: 100
		,custom_field: 'is_image'
		,custom_value: isImage
		,select_fields: 'files.file_id,file_name,file_type,file_size,is_image,image_width,image_height,created_at'
	};

	var store = new Ext.data.JsonStore({
		url: base_url+admin_folder+'tables/browse/files'
		,autoLoad: true
		,paramsAsHash: true
		,remoteSort: true
		,method: 'POST'
		,baseParams: baseParams
		,sortInfo: {
		    field: 'created_at'
		    ,direction: 'DESC'
		}
		,root: 'data'
		,totalProperty: 'total'
		,successProperty: 'success'
		,idProperty: 'file_id'
		,fields: 
		[
			{name: 'file_id'}
			,{name: 'file_name'}
			,{name: 'file_type'}
			,{name: 'file_size'}
			,{name: 'is_image'}
			,{name: 'image_width'}
			,{name: 'image_height'}
			,{name: 'created_at', type:'date', dateFormat:'Y-m-d H:i:s'}
		]
	});

	var tpl = new Ext.XTemplate(
	    '<tpl for=".">'
	        ,'<div class="thumb-wrap" id="{file_name}" title="{is_image}" data-is-image="{is_image}" data-file-id="{file_id}" data-file-name="{file_name}" data-href="'+base_url+'assets/uploads/{file_name}">'
	        ,'<tpl if="is_image == 1"><div class="thumb">{[this.showImg(values.file_name)]}</div></tpl>'
	        ,'<tpl if="is_image == 0"><div class="thumb"><img src="'+base_url+'assets/admin/images/not_available.png" width="100%" title="{file_name}" /></div></tpl>'
	        ,'<span>{file_name}</span>'
	        ,'</div>'
	    ,'</tpl>'
	    ,'<div class="x-clear"></div>'
	    ,{
			showImg: function(fileName){
		        // return fileName.indexOf('.svg') != -1? '<img src="'+base_url+'assets/uploads/'+fileName+'" width="99" title="'+fileName+'" />' : '<img src="'+base_url+'images/load_version/99/99/'+fileName+'" title="'+fileName+'" />';
		        return '<img src="'+base_url+'assets/uploads/'+fileName+'" style="max-width:99px;max-height:99px;" title="'+fileName+'" />';
		    }
		}
	);

	var dataView = new Ext.DataView({
		id: 'dataView'+isImage
        ,store: store
        ,tpl: tpl
        ,multiSelect: true
        ,overClass:'x-view-over'
        ,itemSelector:'div.thumb-wrap'
        ,emptyText: 'No files found!'
        ,listeners:{
			render: function(){
				new ImageDragZone(this, {containerScroll:true, ddGroup: 'group1'});
			}
			,dblclick: function(dataView,index,node,e){
				window.open(node.getAttribute("data-href"),'_blank');
			}
		}
    });

    var panelId    = (isImage)? 'imagesPanel' : 'filesPanel';
    var panelTitle = (isImage)? 'Images' : 'Files';

    var topPaging = new Ext.PagingToolbar({
		pageSize: 100
		,store: store
		,displayInfo: true
		,displayMsg: '{0} - {1} from {2}'
		,emptyMsg: 'No results found'
	});

	var bottomPaging = new Ext.PagingToolbar({
		pageSize: 100
		,store: store
		,displayInfo: true
		,displayMsg: '{0} - {1} from {2}'
		,emptyMsg: 'No results found'
	});

	var search = new Ext.Toolbar({
        items : [
        	{
            	id: 'filesFilter'+isImage
            	,xtype: 'textfield'
            	,width: 200
            }
            ,{
            	xtype:'button'
            	,text: 'Search '+panelTitle
                ,iconCls: 'zoom'
                ,handler: function() {
					var val = Ext.getCmp('filesFilter'+isImage).getValue();
                    if(val) {
                    	store.setBaseParam('filter', Ext.util.JSON.encode([{ type: 'string', field: 'file_name', value: val }]));
                    	store.load(baseParams);
                    }
				}
            }
            ,'-'
            ,{
            	xtype:'button'
            	,text: 'Clear Search'
                ,iconCls: 'refresh'
                ,handler: function() {
					Ext.getCmp('filesFilter'+isImage).setValue('');
                    if(baseParams.filter !== 'undefined') {
                    	delete baseParams.filter;
                    	store.load(baseParams);
                    }
				}
            }
       	]
    });

	var topBar = {
		xtype: 'container'
        ,layout: 'anchor'
        ,height: 54
        ,defaults: { height : 27, anchor : '100%' }
        ,items: [   
            topPaging
            ,search
        ]
    };

    var panel = new Ext.Panel({
		id: panelId
		,title: panelTitle
		,style: {
			backgroundColor: '#FFFFFF'
		}
		,autoScroll: true
		,items: [ dataView ]
		,tbar: topBar
		,bbar: bottomPaging
	});

    return panel;
}

function createImagePanel(imageField,table,tableId,id)
{
	switch(imageField){
		case 'second_image':
			var panelTitle = 'Second Image';
		break;
		case 'third_image':
			var panelTitle = 'Third Image';
		break;
		case 'fourth_image':
			var panelTitle = 'Fourth Image';
		break;
		default:
			var panelTitle = 'Main Image';
		break;

	}
	var panel = new Ext.Panel({
		title: panelTitle
		,autoLoad: {
			url: base_url+admin_folder+'files/load_image'
			,method: 'POST'
			,params: { 
				table: table
				,table_id: tableId
				,id: id
				,image_field: imageField
			}
			,nocache: true
		}
		,width: 200
		,height: 264
		,buttons: [
			{
				xtype: 'button'
				,text: 'Delete Image'
				,iconCls: 'delete'
				,handler: function() {
					Ext.Ajax.request({
						url: base_url+admin_folder+'files/delete_image'
						,method: 'POST'
						,params: { 
							table: table
							,table_id: tableId
							,id: id
							,image_field: imageField
						}
						,success: function() {
							panel.doAutoLoad();
						}
					});
				}
			}
		] 
		,listeners:{
			render: function(){
				new Ext.dd.DropTarget(this.body, {ddGroup:'group1',
					notifyDrop: function(dd, e, data) {
						Ext.Ajax.request({
							url: base_url+admin_folder+'files/update_image'
							,method: 'POST'
							,params: { 
								file_name: data.nodes[0].id
								,table: table
								,table_id: tableId
								,id: id
								,image_field: imageField
							}
							,waitMsg: 'Please wait...'
							,success: function(){
								panel.doAutoLoad();
							}
							,failure: function(){}
						});
					}
				});
			}
		}
	});
	return panel;
}

function filesUpload(galleryId)
{
	galleryId     = 0;
	var grid1     = Ext.getCmp('filesGrid');
	var dataView1 = Ext.getCmp('dataView0');
	var dataView2 = Ext.getCmp('dataView1');

	var awesomeUploader = new Ext.Window({
		title:'Upload Files'
		,iconCls:'add'
		,closeAction:'hide'
		,frame:true
		,width:500
		,items:{
			xtype:'awesomeuploader'
			,gridWidth: 466
			,width:486
			,bodyStyle:'margin:10px'
			,frame:false
	        ,border:false
	        ,disableFlash:true
	        ,maxFileSizeBytes: 31457280
	        ,xhrUploadUrl:base_url+admin_folder+'files/uploadxhr'
			,xhrSendMultiPartFormData:true
	        ,standardUploadFilePostName:'Filedata[]'
			,awesomeUploaderRoot: base_url+'assets/ext/ux/awesomeuploader/'
			,standardUploadUrl: base_url+admin_folder+'files/upload'
			,extraPostData:{
				'csrf_token': csrf_hash
				,'random_string': random_string
				,'gallery_id': galleryId
			}
			,listeners:{
				scope:this
				,fileupload:function(uploader, success, result){
					if(success){
						if(typeof grid1 !== 'undefined'){
							grid1.store.reload();
						}
						if(typeof dataView1 !== 'undefined'){
							dataView1.store.reload();
						}
						if(typeof dataView2 !== 'undefined'){
							dataView2.store.reload();
						}
						if(typeof filesStore !== 'undefined'){
							filesStore.reload();
						}
						
					}
				}
			}
		}
	});
	awesomeUploader.show();
}

function scorePassword(pass) {
    var score = 0;
    if (!pass)
        return score;

    // award every unique letter until 5 repetitions
    var letters = new Object();
    for (var i=0; i<pass.length; i++) {
        letters[pass[i]] = (letters[pass[i]] || 0) + 1;
        score += 5.0 / letters[pass[i]];
    }

    // bonus points for mixing it up
    var variations = {
        digits: /\d/.test(pass),
        lower: /[a-z]/.test(pass),
        upper: /[A-Z]/.test(pass),
        nonWords: /\W/.test(pass),
    }

    variationCount = 0;
    for (var check in variations) {
        variationCount += (variations[check] == true) ? 1 : 0;
    }
    score += (variationCount - 1) * 10;

    return parseInt(score);
}

function reorder(g,myUrl)
{
    var ddrow = new Ext.ux.dd.GridReorderDropTarget(g, {
		copy: false
		,listeners: {
			afterrowmove: function(objThis, oldIndex, newIndex, records) {
				var g = objThis.getGrid();
				var scrollState = g.getView().getScrollState();
	
				g.getEl().mask('Please Wait...','x-mask-loading');
				g.getView().restoreScroll(scrollState);

				var count=0;
				var storeArray = [];
				var serializedStore = false;
	
				g.store.data.each(function() {
					storeArray[count++] = this.data;
				});     
				serializedStore = Ext.encode(storeArray);
				var t = g.getBottomToolbar();
				//var pageNum = Math.ceil((t.cursor + t.pageSize) / t.pageSize);
				var pageNum = Math.ceil(t.cursor);

				Ext.Ajax.request({
					url: myUrl
					,method: 'POST'
					,params: {page:pageNum,data:serializedStore}
					,success: function(response,options) {
						g.getEl().unmask();
						g.getView().restoreScroll(scrollState);
						var ret = null;
						try {
							ret = Ext.util.JSON.decode(response.responseText);;
						} catch(e) {
							Ext.Msg.alert('Error','No data returned from server');
							return;
						}
						if (ret.success) {
							g.store.reload();
							// Ext.Msg.alert('Success','move success');
						} else if (ret.error && ret.error != '') {
							Ext.Msg.alert('Error',ret.error);
						} else {
							Ext.Msg.alert('Error','An error occurred moving the row');
						}
					}
					,failure: function(response,options) {
						g.getEl().unmask();
						g.getView().restoreScroll(scrollState);
	
						Ext.Msg.alert('Error','An error occurred');
					}
					,headers: {'Powered-By': 'Ext'}
				});
			}
		}
	});
    // if you need scrolling, register the grid view's scroller with the scroll manager
    Ext.dd.ScrollManager.register(g.getView().getEditorParent());
}

function refreshToken(){
	Ext.Msg.show({
		title:'Refresh Token',
		msg:'Are you sure you want to refresh it;',
		buttons: Ext.Msg.YESNO,
		icon: Ext.Msg.QUESTION,
		fn: function(btn, text) {
			if(btn == 'yes'){
				Ext.Ajax.request({
					url: base_url+admin_url+'refresh_token'
					,method: "GET"
					,headers: {
						'Powered-By': 'Ext'
					}
				});
				return true;
			}
			return false;
		}
	});
}
