/**
 * @author bumz
 */

Ext.override(Ext.layout.FormLayout, {
	renderItem : function(c, position, target){
		if(c && !c.rendered && (c.isFormField || c.fieldLabel) && c.inputType != 'hidden'){
			var args = this.getTemplateArgs(c);
			if(typeof position == 'number'){
				position = target.dom.childNodes[position] || null;
			}
			if(position){
				c.itemCt = this.fieldTpl.insertBefore(position, args, true);
			}else{
				c.itemCt = this.fieldTpl.append(target, args, true);
			}
			c.actionMode = 'itemCt';
			c.render('x-form-el-'+c.id);
			c.container = c.itemCt;
			c.actionMode = 'container';
		}else {
			Ext.layout.FormLayout.superclass.renderItem.apply(this, arguments);
		}
	}
});
Ext.override(Ext.form.Field, {
	getItemCt : function(){
		return this.itemCt;
	}
});

Ext.form.ComboBox.prototype.filterBy = function(fn, scope) {
	var ds = this.store;
	ds.filterBy(fn, scope);
	ds.realSnapshot = ds.snapshot;
	ds.snapshot = ds.data;
};

Ext.form.ComboBox.prototype.clearFilter = function(suppressEvent) {
	var ds = this.store;
	if (ds.realSnapshot && ds.realSnapshot != ds.snapshot) {
		ds.snapshot = ds.realSnapshot;
		delete ds.realSnapshot;
	}
	ds.clearFilter(suppressEvent);
};

if (Ext.ux.form == undefined) {
    Ext.ns('Ext.ux.form');
}

Ext.ux.form.HtmlEditorCounterPlugin = function (config) {
    Ext.apply(this, config);
};

Ext.extend (Ext.ux.form.HtmlEditorCounterPlugin, Ext.util.Observable, {
    prefix: '',
    itemTypeSingular: 'character',
    itemTypePlural: 'characters',
    itemTypeNone: 'characters',
	itemTypeOf: 'of',
	showOf: true,
    onRender: function (o) {
        this.counter = Ext.get(Ext.DomHelper.append(document.body,{
          tag : 'div',
          style: 'padding-top:2px'
        }));
        this.editor.el.up('div.x-form-element').appendChild(this.counter);
		
		this.ofText = '';
		if (this.showOf && this.editor.maxLength != Number.MAX_VALUE) {
			this.ofText = ' ' + this.itemTypeOf + ' ' + this.editor.maxLength;
		}
		
		if (this.prefix != '') {
			this.prefix += ' ';
		}
		
		this.itemTypeSingular = ' ' + this.itemTypeSingular;
		this.itemTypePlural = ' ' + this.itemTypePlural;
		this.itemTypeNone = ' ' + this.itemTypeNone;
		
        this.set_counter (this.editor);
    },
    init:   function (editor) {
        this.editor = editor;
        this.editor.on ('render', this.onRender, this);
		this.editor.on('valid', this.set_counter, this);
		this.editor.on('invalid', this.set_counter, this);
    },
    set_counter: function (edit) {
		var s = edit.getValue().length;
		//console.log(s);
        this.counter.update( this.prefix + s + ((s) ? ((s > 1) ? this.itemTypePlural: this.itemTypeSingular) : this.itemTypeNone) + this.ofText);
    }
});

Ext.namespace('Linktive');
if (typeof(base_url) != 'undefined') {
	Linktive.base_url = base_url;
}

Linktive.categoriesStore = new Ext.data.Store({
	proxy: new Ext.data.HttpProxy({
		url: Linktive.base_url + 'dashboard/get_sites_categories',
		disableCaching: false
	}),
	reader: new Ext.data.JsonReader({
		totalProperty: 'total',
		successProperty: 'status',
		root: 'results'
	},[ 
		{name: 'key', type: 'int'},
		{name: 'value', type: 'string'}
	]),
	remoteSort: false,
	autoLoad: true,
	listeners: {
		beforeload: function() {
			if (Linktive.base_url === undefined) {
				return false;
			}
		}
	}
});

Linktive.visitorsStore = new Ext.data.Store({
	proxy: new Ext.data.HttpProxy({
		url: Linktive.base_url + 'dashboard/get_sites_visitors',
		disableCaching: false
	}),
	reader: new Ext.data.JsonReader({
		totalProperty: 'total',
		successProperty: 'status',
		root: 'results'
	},[ 
		{name: 'key', type: 'int'},
		{name: 'value', type: 'string'}
	]),
	remoteSort: false,
	autoLoad: true,
	listeners: {
		beforeload: function() {
			if (Linktive.base_url === undefined) {
				return false;
			}
		}
	}
});

Linktive.userSitesStore = new Ext.data.Store({
	proxy: new Ext.data.HttpProxy({
		url: Linktive.base_url + 'dashboard/ajax_get_user_sites',
		disableCaching: false
	}),
	reader: new Ext.data.JsonReader({
		totalProperty: 'total',
		successProperty: 'status',
		root: 'results'
	},[ 
		{name: 'id',				type: 'int'},
        {name: 'site_name',			type: 'string'},
        {name: 'site_url',			type: 'string'},
        {name: 'site_description',	type: 'string'},
        {name: 'site_live',			type: 'int'},
	    {name: 'site_comm',			type: 'int'},
	    {name: 'site_visits',		type: 'int'},
	    {name: 'site_category',		type: 'int'},
	    {name: 'site_active',		type: 'int'},
		{name: 'country',			type: 'string'},
		{name: 'city',				type: 'string'},
	    {name: 'tags',				type: 'string'},
		{name: 'show_link_to_profile', type: 'int'},
		{name: 'show_in_profile',	type: 'int'}
	]),
	remoteSort: false,
	listeners: {}
});

Linktive.userSitesPagesReaderConfig = {
	totalProperty: 'total',
	successProperty: 'status',
	root: 'results'
};

Linktive.userSitesPagesReaderFields = [ 
	{name: 'id',				type: 'int'},
    {name: 'site_name',			type: 'string'},
    {name: 'site_url',			type: 'string'},
    {name: 'site_description',	type: 'string'},
    {name: 'site_live',			type: 'int'},
    {name: 'site_comm',			type: 'int'},
    {name: 'site_visits',		type: 'int'},
    {name: 'site_category',		type: 'int'},
    {name: 'site_active',		type: 'int'},
	{name: 'country',			type: 'string'},
	{name: 'city',				type: 'string'},
    {name: 'tags',				type: 'string'},
	{name: 'show_link_to_profile', type: 'int'},
	{name: 'show_in_profile',	type: 'int'},
	{name: 'parent_site',		type: 'int'}
];

Linktive.userSitesPagesStoreConfig = {
	proxy: new Ext.data.HttpProxy({
		url: Linktive.base_url + 'dashboard/ajax_get_user_sites_pages',
		disableCaching: false
	}),
	reader: new Ext.data.JsonReader(Linktive.userSitesPagesReaderConfig,
									Linktive.userSitesPagesReaderFields),
	remoteSort: true,
	listeners: {}
};

Linktive.userSitesPagesStore = new Ext.data.Store(Linktive.userSitesPagesStoreConfig);

Linktive.userSitesPagesCombo = function(config) {
	
	var cfg = Ext.apply({
		width: 140,
		store: Linktive.userSitesPagesStore,
		allowBlank:false,
		xtype: 'combo',
		valueField:'id',
		displayField:'site_name',
		mode: 'local',
		triggerAction: 'all',
		emptyText: langlines.user_select_page + '...',
		selectOnFocus:true,
		tpl: '<tpl for="."><div ext:qtip="{site_description}" <tpl if="values.parent_site==&quot;0&quot;">class="x-combo-list-item x-item-disabled"</tpl><tpl if="values.parent_site!=&quot;0&quot;">class="x-combo-list-item" style="padding-left: 15px;"</tpl>>{site_name}</div></tpl>',
		listeners: {
			'beforeselect': function(combo, record, index) {
				if(record.get('parent_site') == 0) {
			    	return false;
				}
			}
		}
	}, config)
	return new Ext.form.ComboBox(cfg);
};

Linktive.userSitePagesCombo = Ext.extend(Ext.form.ComboBox, {
	showSites: true,
	showOnlySites: false,
	selectedSite: null,
	isStoreLoaded: false,
	
	width: 140,
	allowBlank:false,
	xtype: 'combo',
	valueField:'id',
	displayField:'site_name',
	mode: 'local',
	triggerAction: 'all',
	emptyText: langlines.user_select_page + '...',
	selectOnFocus:true,
	currentItemId: 0,
	listeners: {
		'beforeselect': function(combo, record, index) {
			if(!combo.showOnlySites && record.get('parent_site') == 0) {
	    		return false;
			}
			return true;
		},
		'select': function(combo, record, index) {
			if (record && record.data && record.data.parent_site == 0) {
				combo.fireEvent('siteselect', combo, record, record.data.id);
			} else {
				combo.fireEvent('pageselect', combo, record, record.data.id, record.data.parent_site);
				combo.setValue(record.data.id);
				combo.currentItemId = record.data.id;
			}
		}, 
		change: function(combo, newValue, oldValue) {
			if (oldValue != newValue) {
				record = combo.store.getById(newValue);
				if (!combo.showOnlySites && record.get('parent_site') == 0) {
					combo.setValue(combo.currentItemId);
				} else {
					combo.setValue(newValue);
				}
			}
		}
	},
	
	initComponent : function() {
		if (this.showSites && !this.showOnlySites) {
			this.tpl = '<tpl for="."><div ext:qtip="{site_description}" <tpl if="values.parent_site==&quot;0&quot;">class="x-combo-list-item x-item-disabled"</tpl><tpl if="values.parent_site!=&quot;0&quot;">class="x-combo-list-item" style="padding-left: 15px;"</tpl>>{site_name}</div></tpl>'
		}
		
		// add events
        this.addEvents(
            /**
             * @event pageselect
             * Fired after user has selected page in selector 
             * @param {Linktive.userSitePagesCombo} combo This combobox
             * @param {Ext.data.Record} record Selected page
             * @param {int} id Id of page selected
             * @param {int} parent_id Id of parent site selected
             */
             'pageselect',
			 
            /**
             * @event siteselect
             * Fired after user has selected site in selector 
             * @param {Linktive.userSitePagesCombo} combo This combobox
             * @param {Ext.data.Record} record Selected site
             * @param {int} id Id of site selected
             */
             'siteselect'
        );
		
		this.store = new Ext.data.Store({
			reader: new Ext.data.JsonReader(Linktive.userSitesPagesReaderConfig,
											  Linktive.userSitesPagesReaderFields)
		});
		
        Linktive.userSitePagesCombo.superclass.initComponent.call(this);
		
		this.isStoreLoaded = false;
		this.makeStore();
    },
	
	makeStore: function() {
		//var comp = this;
		Linktive.userSitesPagesStore.on('load', function(storex, recordsx, optionsx){
			if (this.isStoreLoaded) {
				return true;
			}
			
			var records_to_load = {
				'results' : storex.reader.jsonData.results
			};
			//console.log(records_to_load);
			this.store.loadData(records_to_load, false);
		}, this);
		
		this.store.on('load', function(store, records, options){
			//console.log('load!!');
			this.isStoreLoaded = true;
			//console.log(records, 'internal');
			//console.log(this.store, 'internal');

			if (this.selectedSite) {
				
				var record = store.getById(this.selectedSite);
				//console.log(record, 'selectedSite: ', this.selectedSite);
				if (!record) {
					return true;
				}
				
				if (record.data.parent_site != 0 && this.showSites && this.showOnlySites) { // sites only
					var index = store.findExact('parent_site', record.data.parent_site);
					record = store.getAt(index);
					
					if (!record) {
						return true;
					}
					this.selectedSite = record.data.id;
				} else {
					if (record.data.parent_site == 0 && this.showSites && !this.showOnlySites) { //pages and sites
						//console.log(record, 'linktive');
						var index = store.findExact('parent_site', record.data.id);
						//console.log(index, 'linktive2');
						record = store.getAt(index);
						//console.log(record, 'linktive3');
						if (!record) {
							return true;
						}
						this.selectedSite = record.data.id;
					}
					else {
						if (record.data.parent_site == 0 && !this.showSites && !this.showOnlySites) { //pages only
							var index = store.findExact('parent_site', record.data.id);
							record = store.getAt(index);
							
							if (!record) {
								return true;
							}
							this.selectedSite = record.data.id;
						} else {
							var index = store.indexOf(record);
						}
					}
				}
				
				// need to place it after get value to set into combo
				this.clearFilter();
				
				if (this.pagesOf) {
					this.filterPages(this.pagesOf);
				}
				
				
				
				this.setValue(this.selectedSite);
				this.fireEvent('select', this, record, index);
			}
		}, this);
	},
	
	filterBy: function(fn, scope) {
		var ds = this.store;
		this.store.filterBy(fn, scope);
		this.store.realSnapshot = this.store.snapshot;
		this.store.snapshot = this.store.data;
		//console.log(ds.snapshot, scope, 'snap');
	},

	clearFilter: function(suppressEvent) {
		var ds = this.store;
		if (ds.realSnapshot && ds.realSnapshot != ds.snapshot) {
			ds.snapshot = ds.realSnapshot;
			delete ds.realSnapshot;
		}
		ds.clearFilter(suppressEvent);
		
		this.filterBy(function(item, id){
			if (!this.showSites) {
				/*if ((item.data.parent_site != 0)) {
					console.log('including', item.data.site_name);
				} else {
					console.log('scip', item.data.site_name);
				}*/
				return (item.data.parent_site != 0);
			}
			else {
				if (this.showSites && this.showOnlySites) {
					return (item.data.parent_site == 0);
				}
			}
			return true; //include all items
		}, this);
		//console.log(ds);
	},
	
	filterPages: function(parent_id) {
		this.clearFilter();
		
		this.filterBy(function(item, id){
			if (!this.showSites && this.showOnlySites) {
				return (item.data.parent_site != 0 && (parent_id == item.data.parent_site || parent_id == item.data.id));
			}
			else {
				if (this.showSites && this.showOnlySites) {
					return (item.data.parent_site == 0 && parent_id == item.data.id);
				} else {
					if (!this.showSites && !this.showOnlySites) {
						return (item.data.parent_site != 0 && parent_id == item.data.parent_site);
					}
				}
			}
			return false; // something going wrong :)))))
		}, this);
		
		return this.store.getRange();
	}
});

Linktive.expandTitles = function(titlesClass) {
	var total = 0;
	Ext.each(titlesClass, function(item, index, all) {
		var width = 0;
		if (!item.fixed) {
			width = $(item.selector).outerWidth(true);
		} else {
			if (item.width != 'auto') {
				width = item.width;
			} else {
				width = $(item.selector).outerWidth(true);
				if (item.minWidth && item.minWidth > width) {
					width = item.minWidth;
				}
				if (item.pad) {
					width += item.pad;
				}
				$(titlesClass[index].selector).width(width);
			}
		}
		
		if (item.style) {
			$(item.selector).css(item.style);
		}
		
		titlesClass[index].width = width;
		total += width;
	});
	var container = $(titlesClass[0].selector).parent().outerWidth(true);
	
    if(container < 20){ // not initialized, so don't screw up the default widths
        return;
    }
    var extra = container - total;

    if(extra === 0){
        return false;
    }

    var colCount = titlesClass.length;
    var cols = [];
    var extraCol = 0;
    var width = 0;
    var w;
    for (i = 0; i < colCount; i++){
		if (!titlesClass[i].fixed) {
			w = titlesClass[i].width;
			cols.push(i);
			extraCol = i;
			cols.push(w);
			width += w;
		}
    }
    var frac = (container - total)/width;
    while (cols.length){
        w = cols.pop();
        i = cols.pop();
		$(titlesClass[i].selector).width(Math.max(25, Math.floor(w + w*frac)));
    }
	
	total = 0;
	Ext.each(titlesClass, function(item, index, all) {
		var width = 0;
		if (!item.fixed) {
			width = $(item.selector).outerWidth(true);
		} else {
			if (item.width != 'auto') {
				width = item.width;
			} else {
				width = $(item.selector).outerWidth(true);
				if (item.minWidth && item.minWidth > width) {
					width = item.minWidth;
				}
			}
		}
		total += width;
	});
	
    if(total > container){
        var adjustCol = extraCol;
		$(titlesClass[adjustCol].selector).width(Math.max(1,
                 $(titlesClass[adjustCol].selector).outerWidth() - (total-container)));
    }

    return true;
};

Linktive.syncColumns = function(titles, search, replace) {
	Ext.each(titles, function(item, index, all){
		$(item.selector.replace(search, replace)).width($(item.selector).width());
	});
}


Linktive.question_icon_small = ' <span><div id="{id}" class="question_icon"></div></span>';

Linktive.addQuestionIcon = function(text_id) {
	return {
		'element': Linktive.question_icon_small.replace('{id}', text_id),
		'qtip_init': function() {
			new Ext.ToolTip({
		        target: text_id,
		        html: langlines[text_id]
		    });
		}
	};
};

Linktive.profile_win = null;

Linktive.siteProfileTemplate = '<table id="sid-{id}" class="additional_info quick-tip pseudogrid" style="background: none"> \
								<tr> \
									<td valign="top" class="title no-bottom-padding"> \
										' + langlines.user_site_name + ' \
									</td> \
									<td valign="top" valign="top" class="wide profile_site_name no-bottom-padding"> \
										<div class="profile_site_name"> \
											{site_name} \
										</div> \
										<div class="screenshot"> \
											<img src="{site_thumbnail}" alt="" /> \
										</div> \
									</td> \
									<td valign="top" colspan = "2" class="zero-padding-left no-bottom-padding"> \
										<table> \
											<tbody> \
												<tr> \
													<td valign="top" class="title"> \
														' + langlines.user_site_rate + ': \
													</td> \
													<td  valign="top"> \
														<input type="hidden" id="current-rate-{id}" name="current_rate" value="{rate}" /> \
														<div id="site-rate-{id}" class="profile-site-rate"> \
														</div> \
													</td> \
												</tr> \
												<tr> \
													<td valign="top" class="title"> \
														' + langlines.user_site_inappropriate + ': \
													</td> \
													<td valign="top" class="report_site"> \
														<span id="report-{id}">' + langlines.user_site_report + '</span> \
													</td> \
												</tr> \
												<tr> \
													<td valign="top" class="title no-bottom-padding"> \
														' + langlines.user_is_site_live + ': \
													</td> \
													<td valign="top" class="profile_site_live no-bottom-padding"> \
														{[values.site_live ? langlines.main_yes : langlines.main_no]} \
													</td> \
												</tr> \
											</tbody> \
										</table> \
									</td> \
								</tr> \
								<tpl if="values.show_in_profile==&quot;1&quot;"> \
								<tr> \
									<td valign="top" class="title no-top-padding"> \
										' + langlines.user_site_users_profile + ': \
									</td> \
									<td valign="top" class="no-top-padding"> \
										<div class="profile_link"> \
											<a href="{[base_url + values.username]}">' + langlines.user_site_visit_profile + '</a> \
										</div> \
									</td> \
									<td colspan="2" class="no-top-padding"> \
										&nbsp; \
									</td> \
								</tr> \
								</tpl> \
								<tr> \
									<td valign="top" class="title"> \
										' +langlines.user_web_address + ': \
									</td> \
									<td valign="top" class="profile_site_url"> \
										<div id="quicktip-text-prof-{id}" style="display:none;"> \
											{site_url} \
										</div> \
										<div id="quicktip-handler-prof-{id}"  class="userSiteURLProf"> \
										</div> \
									</td> \
									<td valign="top" class="title"> \
										' + langlines.user_commercial + ': \
									</td> \
									<td valign="top" class="profile_site_comm"> \
										{[values.site_live ? langlines.main_yes : langlines.main_no]} \
									</td> \
								</tr> \
								<tr> \
									<td valign="top" class="title"> \
										' + langlines.user_site_category + ': \
									</td> \
									<td valign="top" class="profile_site_category"> \
										{[langlines["user_site_category_" + values.site_category]]} \
									</td> \
									<td valign="top" class="title"> \
										' + langlines.user_approx_site_visits + ': \
									</td> \
									<td valign="top" class="profile_site_visits"> \
										{[langlines["user_site_users_p_month_" + values.site_visits]]} \
									</td> \
								</tr> \
								<tr> \
									<td valign="top" class="title"> \
										' + langlines.user_description + ': \
									</td> \
									<td valign="top" class="profile_site_description"> \
										{site_description} \
									</td> \
									<td valign="top" class="title"> \
										' + langlines.user_tags + ': \
									</td> \
									<td valign="top" class="profile_tags"> \
										{tags} \
									</td> \
								</tr> \
							</table>';

Linktive.callProfileWin = function(el, values) {
	if (typeof(Linktive.siteProfileTemplate) == 'string') {
		Linktive.siteProfileTemplate = new Ext.XTemplate(Linktive.siteProfileTemplate).compile();
	}
	
	Ext.get(el).win = new Ext.Window({
		layout: 'fit',
		width: 800,
		height: 420,
		closeAction: 'hide',
		plain: true,
		items: [{
			html: '<div class="window_body_profile">' + Linktive.siteProfileTemplate.apply(values) + '</div>'
		}],
		title: langlines.user_profile,
		buttons: [{
			text: langlines.main_ok,
			cls: 'btn_lowercase',
			handler: function(){
				Ext.get(el).win.hide();
			}
		}]
	});
	
	Ext.get(el).win.on('show', function(window){
		win_id = window.getId();
		
		Ext.select('#' + win_id + ' .quick-tip').each(function(e){
			var el = e.dom.id;
			el = el.replace('sid-', '');
			if ($('#quicktip-text-prof-' + el).hasClass('rendered')) {
				return true;
			}
			
			var text = $('#quicktip-text-prof-' + el).text();
			$('#quicktip-text-prof-' + el).addClass('rendered');
			
			new Ext.ToolTip({
				target: 'quicktip-handler-prof-' + el,
				html: text
			});
		});
		
		Ext.select('#' + win_id + ' .profile-site-rate').each(function(e){
			var el = e.dom.id;
			el = el.replace('site-rate-','');
			
			if ($('#rate-holder-' + el).hasClass('x-starslider') || el.match(/container-replace/g)) {
				return;
			}
			
			var rateObj = new Ext.StarSlider({
								id: 'rate-holder-' + el,
				                hiddenName: 'rate-' + el,
								value: $('#current-rate-' + el).val(),
				                renderTo: e.dom.id,
				                minValue: 0,
				                maxValue: 5,
								dragging: false,
								clickToChange: false
				         });
			
			rateObj.on('change', function(){
				this.setDisabled(true);
				var sid = this.getId();
				sid = sid.replace('rate-holder-', '');
				var rateValue = this.getValue();
				Ext.MessageBox.show({
					msg: langlines.main_processing_request,
					progressText: langlines.main_please_wait,
					width:300,
					wait:true,
					waitConfig: {interval:200},
					icon:'download_icon'
				});
				Ext.Ajax.request({
					url: base_url + 'dashboard/ajax_rate_site',
					method: 'POST',
					success: function(responseObject){
						var resultInfo = Ext.util.JSON.decode(responseObject.responseText);
						if(resultInfo.status)
						{
							Ext.MessageBox.hide();
						}
						else
						{
							Ext.MessageBox.hide();
							showWarningMessage(resultInfo.message);
						}
					},
					failure: function(){
						Ext.MessageBox.hide();
						showErrorMessage(langlines.main_server_error);                                                        
					},
					params: {
						'sid' : sid,
						'rate' : rateValue
					}
				});
			});
		});
	});
	
	Ext.get(el).win.show();
};
