var DS = '/';

var myPageSize = 25;

var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;

function ucwords( str ) {
    // *     example 1: ucwords('kevin van zonneveld');
    // *     returns 1: 'Kevin Van Zonneveld'
    // *     example 2: ucwords('HELLO WORLD');
    // *     returns 2: 'HELLO WORLD'
 
    return (str+'').replace(/^(.)|\s(.)/g, function ( $1 ) { return $1.toUpperCase( ); } );
}

function IsNumeric(sText)
{
	var ValidChars = "0123456789.",IsNumber=true,Char;
	for (i=0; i<sText.length && IsNumber==true; i++){
		Char = sText.charAt(i);
		if (ValidChars.indexOf(Char) == -1)
			IsNumber = false;
	}
	return IsNumber;
}

function formatStatus(value){
	var value = (value==0 || value=='0')? 'Unpublished' : (value==2 || value=='2')?'Testing':'Published';
	return value;
}

function formatAccess(value){
	var value = (value==0 || value=='0')? 'Restricted' : (value==2 || value=='2')?'Testing':'Public';
	return value;
}

function formatBoolean(value){
    return value ? 'Yes' : 'No';
}

function formatDate(value){
    return value ? value.dateFormat('Y-m-d') : '';
}

function formatCommenting(value){
	var value = (value==0 || value=='0')? 'Deny' : (value==2 || value=='2')?'Testing':'Allow';
	return value;
}

function formatComAccess(value){
	var value = (value==0 || value=='0')? 'Registered' : (value==2 || value=='2')?'Testing':'All';
	return value;
}

function formatComPublish(value){
	var value = (value==0 || value=='0')? 'Manual' : (value==2 || value=='2')?'Testing':'Auto';
	return value;
}

function formatComEmail(value){
	var value = (value==0 || value=='0')? 'No' : (value==2 || value=='2')?'Testing':'Yes';
	return value;
}

function formatSubscribe(value){
	var value = (value==0 || value=='0')? 'Deny' : (value==2 || value=='2')?'Testing':'Allow';
	return value;
}

function formatFollowers(value){
	var value = (value==0 || value=='0')? 'Deny' : (value==2 || value=='2')?'Testing':'Allow';
	return value;
}

function zeroFill(number, length) {
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
    return str;
}


var statusStore = new Ext.data.SimpleStore({
	fields: ['idx', 'txt'],
	data : [['0', 'Unpublished'],['1', 'Published'],['2', 'Testing']]
});

var statusStoreWithoutTesting = new Ext.data.SimpleStore({
	fields: ['idx', 'txt'],
	data : [['0', 'Unpublished'],['1', 'Published']]
});
var stickyStoreWithoutTesting = new Ext.data.SimpleStore({
	fields: ['idx', 'txt'],
	data : [['0', 'No'],['1', 'Yes']]
});
var statusStoreWithoutTestingFilter = new Ext.data.SimpleStore({
	fields: ['idx', 'txt'],
	data : [['-1', '(Reset Filter)'],['0', 'Unpublished'],['1', 'Published']]
});

var accessStore = new Ext.data.SimpleStore({
	fields: ['idx', 'txt'],
	data : [['0', 'All Users'],['1', 'Registered Users Only']]
});

function is_array(mixed_var) {
    return ( mixed_var instanceof Array );
}

function str_replace(search, replace, subject) {
    var f = search, r = replace, s = subject;
    var ra = is_array(r), sa = is_array(s), f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;

    while (j = 0, i--) {
        while (s[i] = s[i].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
    };

    return sa ? s : s[0];
}

Array.prototype.inArray = function(element) {
	return this.indexOf(element) !== -1;
};


function in_array(needle, haystack) {
	for (var i in haystack)
		if (haystack[i]==needle) return true;
	return false;
}

function getImgageSize(imgSrc) {
	var newImg = new Image();
	newImg.src = imgSrc;
	return {width:newImg.width,height:newImg.height};
}
/* pull sites for which user has access */
var sitesDataRecord = Ext.data.Record.create([
	{name: 'id'},
	{name: 'display_name'},
	{name: 'iconCls'},
	{name: 'parent_id'}
]);
function getSitesStore() {
	var sitesDropStore = new Ext.data.Store({
	    proxy: new Ext.data.HttpProxy({
			url: '/sites/getAll'
		}),
		autoLoad: false,
	    reader: new Ext.data.JsonReader({
			    root:'results',
				totalProperty: 'total',
				id: 'id'
	    	}, sitesDataRecord),
	    remoteSort: true
	});
	sitesDropStore.on('loadexception', function() {
	  alert('Error loading system sites!');
	});
	return sitesDropStore;
}

function getUsersStore(autoLoad) {
	var usersDropStore = new Ext.data.Store({
	    proxy: new Ext.data.HttpProxy({
			url: '/users/getAll'
		}),
		autoLoad: autoLoad,
	    reader: new Ext.data.JsonReader({
			    root:'results',
				totalProperty: 'total',
				id: 'id'
	    	}, [
				{name: 'id'},
				{name: 'username'}
			]),
	    remoteSort: true
	});
	usersDropStore.on('loadexception', function() {
	  alert('Error loading users!');
	});
	return usersDropStore;
}




/* Delete function */
var Delete = function(_grid,_url,_itemName) {
	if (!_itemName) _itemName = 'item';
	
    // get the selected items
    var m = _grid.getSelections();
    if(m.length > 0) {
    	Ext.MessageBox.confirm('Delete '+_itemName+'?',
    	    'Do you really want to delete the selected '+_itemName+'?',
    	    function(btn) {
	    	     if(btn == 'yes'){
		            var removedData;
		            for(var i = 0, len = m.length; i < len; i++){
		                var ss = m[i].get("id");
		                if(i===0){
							removedData = ss;
						} else {
		                    removedData += "," + ss;
						}
		                //ds.remove(m[i]);
					}
					_grid.el.mask("Please wait...Deleting!",'x-mask-loading');
					Ext.Ajax.request({
						url: _url,
						scope: this,
						method:'GET',
						params: { 'delData': removedData },
						success: function(response, options) {
							_grid.el.unmask();
							if(Ext.decode(response.responseText).success === false) {
								Ext.Msg.alert('Error', Ext.decode(response.responseText).errorInfo);
							} else {
								_grid.store.load({params:_grid.store.lastOptions.params});
							}
						}
					});
			    }
		    }
		);
    } else {
    	Ext.MessageBox.alert('No '+_itemName+' selected!', 'Please select at least one '+_itemName+'!');
    }
};

var DeleteFromTree = function(_tree,_url,_id,_itemName) {
	if (!_itemName) _itemName = 'item';
    if(_id > 0){
    	Ext.MessageBox.confirm('Delete '+_itemName+'?',
    	    'Are you sure you want to delete this '+_itemName+'?',
    	    function(btn) {
	    	     if(btn == 'yes'){
					_tree.el.mask("Please wait...Deleting!",'x-mask-loading');
					Ext.Ajax.request({
						url: _url,
						scope: this,
						method:'GET',
						params: {'delData': _id},
						success: function(response, options) {
							if(Ext.decode(response.responseText).success === false) {
								_tree.el.unmask();
								Ext.Msg.alert('Error', Ext.decode(response.responseText).errorInfo);
							} else {
								_tree.el.unmask();
								_tree.root.reload();
							}
						}
					});
			    }
		    }
		);
    } else {
    	Ext.MessageBox.alert('No '+_itemName+' Selected!', 'Please select an '+_itemName+' to delete!');
    }
};

/* Change Status function */
var ChangeStatus = function(_grid,_status,_url,_itemName) {
	
	if (!_itemName) _itemName = 'item';
	
    // get the selected items
    var removedData = _grid.getSelectedIds();
    
    if(removedData.length > 0) {
		_grid.el.mask("Please wait...!",'x-mask-loading');
		Ext.Ajax.request({
			url: _url,
			scope: this,
			method:'POST',
			params: { 'delData': removedData, 'status': _status },
			success: function(response, options) {
				_grid.el.unmask();
				if(Ext.decode(response.responseText).success === false) {
					Ext.Msg.alert('Error', Ext.decode(response.responseText).errorInfo);
				} else {
					_grid.store.load({params:_grid.store.lastOptions.params});
				}
			}
		});
    } else {
    	Ext.MessageBox.alert('No '+_itemName+' selected!', 'Please select at least one '+_itemName+'!');
    }
};

var positionsRecord = Ext.data.Record.create([
	{name: 'alias'},
	{name: 'name'}
]);
var positionsStore = new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
		url: '/positions/getAll?sort=alias'
	}),
    reader: new Ext.data.JsonReader({
        root:'results'
    }, positionsRecord)
});

positionsStore.on('loadexception', function() {
  alert('error loading module positions');
});


var stylesStore = new Ext.data.JsonStore({
  url: '/positions/getStyles',
  root: 'results',
  fields: [ 'alias', 'name' ]
});

stylesStore.on('loadexception', function() {
  alert('error loading position styles');
});

var aclStore = new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
		url: '/roles/getCustomAcl'
	}),
    reader: new Ext.data.JsonReader({
        root:'results'
    }, [
		{name: 'acos'}
	])
});

aclStore.on('loadexception', function() {
  	alert('error loading custom acl');
});

function trace(obj,values) {
	var s='', values=(values?values:{});
	for (i in obj) {
		s+=i+' ';
		if (values===true) {
			s+=' - '+obj[i];
		} else {
			if (values[i]) s+=' : '+obj[i];
		}
		
		
		s+='| ';
	}
	alert(s);
}
function debug(el) {
	if (console) console.log(el);
	else trace(el);
}

function hideBarItems(bar) {
	for (var i=0; i<bar.items.length; i++) {
		if (bar.items.items[i].hide)
			bar.items.items[i].hide();
	}
}

function changeCommenting(value) {
	if (value=='1') {
		Ext.getCmp('fldSetCommenting').show();
		Ext.getCmp('com_accessF').enable();
		Ext.getCmp('com_publishF').enable();
		Ext.getCmp('com_emailF').enable();
		Ext.getCmp('fldSetCommenting').doLayout();
	} else {
		Ext.getCmp('fldSetCommenting').hide();
		Ext.getCmp('com_accessF').disable();
		Ext.getCmp('com_publishF').disable();
		Ext.getCmp('com_emailF').disable();
	}
}

function getCommentingFields(_model,_moderators) {
	var commentingData = new Ext.data.SimpleStore({
		fields: ['idx', 'txt'],
		data : [['0', 'Deny'],['1', 'Allow']]
	});
	
	var commentingField = new Ext.form.ComboBox({
		editable: false,
		id:'commenting',
		name:'commenting',
		fieldLabel: 'Commenting',
		store: commentingData,
		displayField:'txt',
		dataIndex: 'commenting',
		value: '0',
		typeAhead: false,
		selectOnFocus:true,
		valueField: 'idx',
		hiddenName: 'data['+_model+'][commenting]',
		triggerAction: 'all',
		width: 150,
		allowBlank: false,
		mode: 'local',
		listeners:{
			'select':{
				fn: function(record,combo) {
					changeCommenting(record.value);
				}
			},
			'render':{
				fn: function() {
					// get form and set listener
					var form = this.findParentByType('form');
					form.addListener('actioncomplete',function(thisForm, action) {
						if(action.type=='load') {
	    					changeCommenting(thisForm.reader.jsonData.results[0].commenting);
						}
					},true);
				}
			}
		}
	});
	
	
	var comAccessData = new Ext.data.SimpleStore({
		fields: ['idx', 'txt'],
		data : [['0', 'Registered Users'],['1', 'All Users']]
	});

	var comAccessField = new Ext.form.ComboBox({
		editable: false,
		id:'com_accessF',
		name:'com_access',
		value: 1,
		fieldLabel: 'Commenting Access',
		store: comAccessData,
		displayField:'txt',
		dataIndex: 'com_access',
		typeAhead: false,
		selectOnFocus:true,
		valueField: 'idx',
		hiddenName: 'data['+_model+'][com_access]',
		triggerAction: 'all',
		width: 150,
		listWidth: 160,
		allowBlank: false,
		disabled: true,
		mode: 'local'
	});
	
	var comPublishData = new Ext.data.SimpleStore({
		fields: ['idx', 'txt'],
		data : [['0', 'Manual'],['1', 'Auto'],['2','Auto-publish if registered']]
	});

	var comPublishField = new Ext.form.ComboBox({
		editable: false,
		id:'com_publishF',
		name:'com_publish',
		value: 1,
		fieldLabel: 'Commenting Publish',
		store: comPublishData,
		displayField:'txt',
		dataIndex: 'com_publish',
		typeAhead: false,
		selectOnFocus:true,
		valueField: 'idx',
		hiddenName: 'data['+_model+'][com_publish]',
		triggerAction: 'all',
		width: 150,
		listWidth: 160,
		allowBlank: false,
		disabled: true,
		mode: 'local'
	});
	
	var comEmailData = new Ext.data.SimpleStore({
		fields: ['idx', 'txt'],
		data : [['0', 'Don\'t Send'],['1', 'Send email to owner']]
	});

	var comEmailField = new Ext.form.ComboBox({
		editable: false,
		id:'com_emailF',
		name:'com_email',
		value: 0,
		fieldLabel: 'Commenting Email',
		store: comEmailData,
		displayField:'txt',
		dataIndex: 'com_email',
		typeAhead: false,
		selectOnFocus:true,
		valueField: 'idx',
		hiddenName: 'data['+_model+'][com_email]',
		triggerAction: 'all',
		width: 150,
		listWidth: 160,
		allowBlank: false,
		disabled: true,
		mode: 'local'
	});
	
	if (_moderators) {
		var commModerators = new Ext.ux.form.SuperBoxSelect({
			id:'moderators_sbs',
	        allowBlank:true,
			msgTarget: 'title',
	        xtype:'superboxselect',
	        fieldLabel: 'Additional Moderators',
	        resizable: true,
	        anchor:'100%',
	        store: getUsersStore(true),
	        mode: 'local',
	        displayField: 'username',
	        valueField: 'id',
	        queryDelay: 0,
	        hiddenName: 'data['+_model+'][com_moderators][]',
			triggerAction: 'all',
			minChars: 1,
			dataIndex: 'com_moderators'
	     });
	}
     
	var reqCommEmail = new Ext.form.Checkbox({
    	fieldLabel:'Require Email Authentication',
    	checked: false,
    	dataIndex: 'com_req_email',
    	name: 'data['+_model+'][com_req_email]'
    });
    
    var fieldsetItems = [comAccessField, comPublishField, comEmailField];
	if (_moderators) {
		fieldsetItems.push(	commModerators);
	}
	fieldsetItems.push(reqCommEmail);
	
	return {'field':commentingField,
			'fieldset':{
				xtype:"fieldset",
				id: 'fldSetCommenting',
				title:'Commenting Settings',
				collapsible:true,
				autoHeight:true,
				hidden: true,
				width:500,
				items:fieldsetItems
        	}};
}

function getTagsSelector(_controller,_model,_selectedId) {
	if (!_selectedId) _selectedId = 0;
	var fromData = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: '/tags/getAvailableTags/'+_selectedId
        }),
		autoLoad:true,
        reader: new Ext.data.JsonReader({
            root: 'results',
            id: 'id'
        }, [
            {name: 'id'},
            {name: 'name'}
        ]),
		sortInfo: {field: "name", direction: "ASC"},
        remoteSort: true
    });
	var toData = new Ext.data.Store({
        baseParams: { id: _selectedId },
		proxy: new Ext.data.HttpProxy({
             url: '/'+_controller+'/getTags/'+_selectedId
        }),
		autoLoad:true,
        reader: new Ext.data.JsonReader({
            root: 'results',
            id: 'id'
        }, [
            {name: 'id'},
            {name: 'name'}
        ]),
		sortInfo: {field: "name", direction: "ASC"},
        remoteSort: true
    });
    return {
			xtype:"itemselector",
			name:"data[Tags]",
			fieldLabel:"Tags",
			dataFields:["id", "name"],
			fromStore:fromData,
			bodyStyle:"background:transparent",
			toStore:toData,
			width: 500,
			msWidth:162,
			msHeight:150,
			valueField:"id",
			displayField:"name",
			drawUpIcon:false,
			drawDownIcon:false,
			drawTopIcon:false,
			drawBotIcon:false,
			toLegend:"Selected Tags",
			fromLegend:"Available Tags",
			toTBar:[{
				text:"Clear",
				handler:function() {
					var i=this.findParentByType('form').getForm().findField("data[Tags]");
					i.reset.call(i);
				}
			}]
		};
}

function GetOriginalBreadcrumbs(div_id){
	if (!div_id) div_id='breadcrumbs';
	var div = document.getElementById(div_id);
	if (div) return div.innerHTML;
	else return '';
}

function GetBreadcrumbsContainer(div_id){
	if (!div_id) div_id='breadcrumbs';
	
	var div = document.getElementById(div_id);
	if (div) return div;
	else return {};
}

function utf8_encode ( argString ) {
    var string = (argString+'').replace(/\r\n/g, "\n").replace(/\r/g, "\n");
 
    var utftext = "";
    var start, end;
    var stringl = 0;
 
    start = end = 0;
    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;
 
        if (c1 < 128) {
            end++;
        } else if((c1 > 127) && (c1 < 2048)) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc !== null) {
            if (end > start) {
                utftext += string.substring(start, end);
            }
            utftext += enc;
            start = end = n+1;
        }
    }
 
    if (end > start) {
        utftext += string.substring(start, string.length);
    }
 
    return utftext;
}

function utf8_decode ( str_data ) {
    var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0;
    
    str_data += '';
    
    while ( i < str_data.length ) {
        c1 = str_data.charCodeAt(i);
        if (c1 < 128) {
            tmp_arr[ac++] = String.fromCharCode(c1);
            i++;
        } else if ((c1 > 191) && (c1 < 224)) {
            c2 = str_data.charCodeAt(i+1);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i+1);
            c3 = str_data.charCodeAt(i+2);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }
 
    return tmp_arr.join('');
}

function base64_encode( data ) {
	var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc="", tmp_arr = [];

	if (!data) {
		return data;
	}
	
	data = utf8_encode(data+'');

	do { // pack three octets into four hexets
		o1 = data.charCodeAt(i++);
		o2 = data.charCodeAt(i++);
		o3 = data.charCodeAt(i++);

		bits = o1<<16 | o2<<8 | o3;

		h1 = bits>>18 & 0x3f;
		h2 = bits>>12 & 0x3f;
		h3 = bits>>6 & 0x3f;
		h4 = bits & 0x3f;

		// use hexets to index into b64, and append result to encoded string
		tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
	} while (i < data.length);

	enc = tmp_arr.join('');

	switch( data.length % 3 ){
		case 1:
		enc = enc.slice(0, -2) + '==';
		break;
		case 2:
		enc = enc.slice(0, -1) + '=';
		break;
	}

	return enc;
}

function base64_decode( data ) {
	var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = "", tmp_arr = [];

	if (!data) {
		return data;
	}

	data += '';

	do {  // unpack four hexets into three octets using index points in b64
		h1 = b64.indexOf(data.charAt(i++));
		h2 = b64.indexOf(data.charAt(i++));
		h3 = b64.indexOf(data.charAt(i++));
		h4 = b64.indexOf(data.charAt(i++));

		bits = h1<<18 | h2<<12 | h3<<6 | h4;

		o1 = bits>>16 & 0xff;
		o2 = bits>>8 & 0xff;
		o3 = bits & 0xff;

		if (h3 == 64) {
			tmp_arr[ac++] = String.fromCharCode(o1);
		} else if (h4 == 64) {
			tmp_arr[ac++] = String.fromCharCode(o1, o2);
		} else {
			tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
		}
	} while (i < data.length);

	dec = tmp_arr.join('');
	dec = utf8_decode(dec);

	return dec;
}
function _GET(name)
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, '%20'));
}