// ----- Define superflousEffects as global var for automaticaly chenged z-index for windows
var superflousEffects = true;

// --- Main Class realized all Functionality for user part -----------------
var UserAction = {
	chache_states: {},
	local_login: true,
	form_ids:{
		login_form: 'login_form',
		login_form_static: 'login_form_static',
		forgot_form: 'forgot_form',
		change_password_form: 'change_password_form',
		registration_form: 'registration_form',
		user_info_form: 'user_info_form',
		send_report_form: 'send_report_form',
		manage_notification_form: 'manage_notification_form',
		change_email_form: 'change_email_form',
		new_message_form: 'new_message_form'
	},
// --- Login Functions
	closeNewMessageWin: function(){
		this.new_message_win.hide();
	},

	initNewMessage: function(){
		this.new_message_win.new_form = new ITcraft.ajaxForm({
			form: this.form_ids['new_message_form'],
			listeners: {
				onSuccess: function(d) {
					this.closeNewMessageWin();
					if(d.target){
						document.location = d.target;
					}
				},
				scope: this
			}
		});
	},

	userLogin: function (redirect_to){
		this.login_taget_url = redirect_to ? redirect_to : null;
		
		if (!this.login_win) {
			this.login_win = ITcraft.ut.getDialog({
				id: 'login_win',
				width: 320,
				height: 460
			},{
				ajax_content: {
					parameters: {
						type: 'login_form'
					}
				},
				formConfig: {
					listeners: {
						onSuccess: function(d) {
							if (this.local_login) {
								if (this.login_taget_url) {
									var c = this.login_taget_url;
									if (typeof c == 'string') {
										location.href = c;
									} else if (typeof c == 'object' || typeof c == 'function') {
										if (typeof c == 'function') {
											c();
										} else if (typeof c.fn == 'function' && c.scope) {
											c.fn.apply(c.scope);
										}
									}
								} else {
									var p = document.location.pathname;
									if (p == '/logout/' || p == '/logout') {
										document.location = '/';
									} else {
										history.go(0);
									};
								};
							} else if (d.target) {
								document.location = d.target;
							} else {
								document.location = '/';
							};
						},
						scope: this
					}
				}
			});
		}
		this.login_win.show();
	},

	userForgot: function (){
		if (!this.forgot_pass_win) {
			this.forgot_pass_win = ITcraft.ut.getDialog({
				id: 'forgot_win',
				width: 260,
				height: 200
			},{
				ajax_content: {
					parameters: {
						type: 'forgot_password_form'
					}
				}
			});
		}
		this.forgot_pass_win.show();
	},
	showChangePasswordWin: function(old_password){
		if(!this.change_pass_win){
			this.change_pass_win = ITcraft.ut.getDialog({
				id: 'change_win',
				width: 340,
				height: 245
			},{
				ajax_content: {
					parameters: {
						type: 'change_password_form',
						old_password: old_password
					}
				}
			});
		}
		this.change_pass_win.show();
	},
/*******************************************************************************
 * Registration Process Functionality
 ******************************************************************************/
	onChangeCountry: function(c_selector, state_selector_id, mask_el, back, state_id) {
		var country_id = c_selector.value;
		var state_selector = $(state_selector_id);
		if (state_selector) {
			if(country_id == 0){
				this.updateStateSelector(state_selector, {0: "Any"});
				return true;
			}
			if (this.chache_states && this.chache_states[country_id]) {
				this.updateStateSelector(state_selector, this.chache_states[country_id], state_id);
			} else {
				this.current_state_selector = state_selector;
				this.current_mask_el = mask_el ? mask_el : null;
				if (this.current_mask_el) {
					ITcraft._loadMask(this.current_mask_el, true);
				};
				ITcraft.request('ajax_getstates_list.php', {
					parameters: {country_id: country_id},
					onSuccess: function(json, response){
						var list = null;
						if (json && json['country_id'] > 0) {
							if (json['data']) {
								list = json['data'];
							}
							this.chache_states[json['country_id']] = list;
						}
						this.updateStateSelector(this.current_state_selector, list, state_id);
						if (this.current_mask_el) {
							ITcraft._loadMask(this.current_mask_el, false);
						}
					},
					scope: this
				});
			}
		}
	},
	updateStateSelector: function(selector, list, state_id) {
		if (!selector) return null;
		var l = [];
		if (list) {
			for(var i in list) {
				l.push({v: i, t: list[i]});
			};
		};
		if (selector.disabled) selector.disabled = false;
		if (l.length == 0) {
			selector.disabled = true;
			return true;
		} else if (l.length == 1) {
			//check if this is 'empty list', without states list was returned
			if (l[0].v < 1) {
				selector.disabled = true;
			};
		};
		while(selector.options.length > 0) {
			selector.remove(0);
		};

		var c = 0;
		var sel = (!state_id) ? 0: state_id;

		for(var i=0; i<l.length; i++) {
			var newOpt = new Option(l[i].t, l[i].v);
			if(sel == l[i].v){
				c = i;
			}
			try {
				selector.add(newOpt, null);
			}
			catch(ex) {
				selector.add(newOpt); //IE only
			}
		}
		selector.selectedIndex = c;
	},
	requstrationOnTypeChange: function(mode) {
		if (mode == 'buyer') {
			v = 'none';
		} else {
			v = '';
		};

		if (this.reg_type_cache && this.reg_type_cache == v) return;
		var el_ids = ["paypal_account_row1", "paypal_account_row2"];
		for(var i=0; i<el_ids.length; i++) {
			var el = $(el_ids[i]);
			if (el) {
				el.style.display = v;
			}
		}
	},
	initRegistration: function() {
		this.registration_form = new ITcraft.ajaxForm({
			form: this.form_ids['registration_form'],
			mask_element: "mask_container",
			listeners: {
				onSuccess: function(d) {
					//$(this.form_ids['registration_form']).update(d.message_ok);
					document.location = d.target ? d.target : '/users/register/thankyou-buyer/';
				},
				scope: this
			}
		});
		this.login_form_static = new ITcraft.ajaxForm({
			form: this.form_ids['login_form_static'],
			mask_element: "mask_container_login",
			listeners: {
				onSuccess: function(d) {
					document.location = d.target;
				},
				scope: this
			}
		});
	},
/***** manage profile page [start] *****/
	initEditProfile: function(){
		this.edit_profile_form = new ITcraft.ajaxForm({
			form: this.form_ids['user_info_form']
		});
		var maxChars = parseInt($('box_count_characters').innerHTML,10);
		new ITcraft.ut.charsCounter({
			field:$('about_textarea'),
			counter_box:$('box_count_characters'),
			max_chars:maxChars > 0 ? maxChars : 500
		});
	},
	addWatermark: function() {
		ITcraft.request('/ajajx/manage_profile.php?cmd=avatar_addwatermark',{
			onSuccess: function(json, resp) {
				$("profile_user_photo").src = json.new_photo;
			},
			scope: this
		});
	},
	changeImageWin: function(){
		if(!this.image_win){
			this.image_win = ITcraft.ut.getDialog({
				id: 'image_win',
				width: 450,
				height: 230
			},{
				ajax_content: {
					parameters: {
						type: 'change_avatar_form'
					}
				},
				formConfig: {
					listeners: {
						onSuccess: function(d) {
							$('profile_user_photo').src = d.new_photo;
							this.image_win.hide();
						},
						scope:this
					}
				}
			});
		};
		this.image_win.show();
	},
	changeImage: function(){
		this.image_win.form.submit();
	},
	removeImage: function(){
		ITcraft.showConfirm('Are you sure you want to remove your avatar?', 'Confirm', this.sendRemoveImage, this);
	},
	sendRemoveImage: function(){
		var requestData = new Ajax.Request('/ajax/manage_profile.php?cmd=avatar_remove',{
			method: 'get',
			onSuccess: function(transport, json) {
				$('profile_user_photo').src = json.new_photo;
				UserAction.showAlert(json.messages[0]);
				UserAction.closeImageWin();
			}
		});
	},
/***** manage profile page [end] *****/ 
	showSendMessageWindow: function(brand_id){
		if(!this.report_win){
			this.report_win = new UI.Window({
				id: 'report_win',
				shadow:true,
				width: 420,
				height: 285,
				close: 'hide'
			});
			var url = 'user_ajax_brands.php?cmd=get_report_form&brand_id='+brand_id;
			var requestData = new Ajax.Request(url,{
				method: 'get',
				onSuccess: function(transport, json) {
					UserAction.report_win.setContent(transport.responseText);
					UserAction.initSendReport();
				}
			});
			this.report_win.setHeader('Send the Message to Administrator');
			this.report_win.setZIndexWithShadow(220);
		}
		this.report_win.center();
		this.report_win.show();
		if (this.report_win.new_form) {
			// this.report_win.new_form.form.elements[1]._changed = false;
			this.report_win.new_form.reset();
		}
		this.report_win.activate();
	},
	resetInitText: function(el) {
		if (!el._changed) {
			el.value = '';
		}
	},
	initSendReport: function(){
		this.report_win.new_form = new ITcraft.ajaxForm({
			form: this.form_ids['send_report_form'],
			listeners: {
				onSuccess: function(d) {
					this.closeReportWin();
				},
				onFail: function(d) {
				},
				scope: this
			}
		});
	},
	closeReportWin: function(){
		this.report_win.hide();
	},
	showSendEmailMessageWindow: function(){
		if(!this.report_email_win){
			this.report_email_win = new UI.Window({
				id: 'report_email_win',
				shadow: true,
				width: 430,
				height: 380,
				close: 'hide'
			});
			var url = '/http/get_dialog.php?cmd=get_report_email_form';
			ITcraft.request(url,{
				onSuccess: function(json, response) {
					this.report_email_win.setContent(response);
					this.initSendEmailReport();
				},
				scope: this
			});
			//this.report_email_win.setHeader('Report Bug to Administrator');
			this.report_email_win.setZIndexWithShadow(220);
		}

		this.report_email_win.center();
		this.report_email_win.show();
		if (this.report_email_win.new_form) {
			this.report_email_win.new_form.resetTextArea();
			this.report_email_win.new_form.reset();
		}
		this.report_email_win.activate();
	},
	initSendEmailReport: function(){
		this.report_email_win.new_form = new ITcraft.ajaxForm({
			form: 'send_email_report_form',
			listeners: {
				onSuccess: function(d) {
					this.closeReportEmailWin();
				},
				scope: this
			},
			resetTextArea: function() {
				this.form.elements[1]._changed = false;
			}
		});
	},
	closeReportEmailWin: function(){
		this.report_email_win.hide();
	},
	searchEmail: function(id, url){
		var search = $(id).getValue();
		if(search == '' ){
			ITcraft.showAlert('Search keywords must be entered.', 'Notice');
			return false;
		}else{
			document.location = url+'&search_string='+search;
		}

	},
	initNotifications: function(){
		new ITcraft.ajaxForm({
			mask_element: 'mask_notif',
			form: this.form_ids['manage_notification_form'],
			listeners: {
				onSuccess: function(d) {
				},
				onFail: function(d) {
				},
				scope: this
			}
		});
	},
	showUpdateEmailWin: function(){
		if(!this.up_email_win){
			this.up_email_win = ITcraft.ut.getDialog({
				id: 'up_email_win',
				width: 350,
				height: 300
			},{
				//header: 'Change Email',
				ajax_content: {
					parameters: {
						type: 'change_email_form'
					}
				},
				formConfig: {
					listeners: {
						onSuccess: function(d, R) {
							$('user_email_box').innerHTML = R.request.options.parameters['f[email]'];
							this.up_email_win.hide();
						},
						scope: this
					}
				}
			});
		};
		this.up_email_win.show();
	},
	loginPlease: function(){
		var msg = '<center>You must be logged in. <a onclick="UserAction.userLogin();" class="class_pointer">Log In</a> or <a class="top_nav_red" href="/users/register/">Sign Up</a></center>';
		ITcraft.showAlert(msg);
	},
	defaultConfirm: function(url, msg){
		var buttons = {
			ok: '   Ok   ',
			cancel: '    Cancel    '
		};
		ITcraft.showConfirm(msg, 'Message', function(){
			document.location=url;
		}, this, null, buttons);
	},
//TODO remove
	showDomainTip: function(id, action){
		if(!action){
			this.timeout = setTimeout(function hideTip(){$(id).hide();}, 2000);
		}
		if(action == 'hide'){
			$(id).hide();
		}else{
			$(id).show();
		}
		if(action == 'show'){
			clearTimeout(this.timeout);
		}
	}
};

var itemAlreadyInCart = function() {
	ITcraft.showAlert('This item is already in your shopping cart!', 'Shopping Cart');
};

/** * new ** */
var SearchMain = {
	sc: null,
	init: function(){
		var sc = $('search_contener_header');
		if(sc) {
			sc.observe('click', this.hideLabel.bind(this));
			sc.observe('blur', this.showLabel.bind(this));
			this.defaultValue=sc.getValue();
			this.sc = sc;
		}
	},
	hideLabel: function(el){
		if(this.defaultValue == this.sc.getValue()){
			this.sc.setValue('');
		}
	},
	showLabel: function(el){
		if(this.sc.getValue() == ''){
			this.sc.setValue(this.defaultValue);
		}
	},
	submit_: function() {
		if(this.defaultValue == this.sc.getValue()){
			return false;
		};
		return true;
	}
};

var BasePage = {
	conf: null,
	
	isLogged:function(not_display_login_dialog) {
		if (user_id > 0) {
			return true;
		};
		if (not_display_login_dialog) {
			return false;
		};
		UserAction.userLogin();
	}
};

var ReportThis = function(config){
	if (config) {
		ITcraft.apply(this, config);
	}
};
ReportThis.prototype = {
	type: null,
	item_id: null,

	for_feedback: false,
	feeadback_object_id: null,

	win: null,

	_check: function() {
		return this.type && this.item_id;
	},
	
	show: function() {
		if (!this._check()) return;
		if (!this.win) {
			this.win = ITcraft.ut.getDialog({
				width: 400,
				height: 280
				// close: 'destroy',
				// auto: false
			},{
//				header: 'Send the Message to Administrator',
				ajax_content: {
					parameters: {
						type: 'report_this',
						subtype: this.type,
						item_id: this.item_id,
						// for_feedback: this.for_feedback,
						feeadback_object_id: this.feeadback_object_id
					}
				}
			});
		}
		this.win.show();
	}
};
