// ----- 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);
				}
				var url = "ajax_getstates_list.php";
				ITcraft.request(url, {
					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 (l.length == 0) {
			selector.disabled = true;
			return 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
			}
		});
	},
// ------------- Edit Profile Functionality --------------------------
	initEditProfile: function(){
		this.edit_profile_form = new ITcraft.ajaxForm({
			form: this.form_ids['user_info_form']
		});
		var c_counter = new ITcraft.ut.charsCounter({
			field: $('about_textarea'),
			counter_box: $('box_count_characters')
		});
	},
	addWatermark: function() {
		ITcraft.request('/editprofile.php?cmd=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: 380,
				height: 265
			},{
//				header: 'Change Avatar',
				ajax_content: {
					parameters: {
						type: 'change_avatar_form'
					}
				}
			});
		}
		this.image_win.show();
	},
	changeImage: function(){
		// $("iframe_change_image");
		var id = 'iframe_change_image';
		var frame = document.createElement('iframe');
		frame.id = id;
		frame.name = id;
		frame.className = 'x-hidden';

		if(Prototype.Browser.IE){
			frame.src = 'javascript: false;';
		}
		document.body.appendChild(frame);
		if(Prototype.Browser.IE){
			document.frames[id].name = id;
		}
		$('change_image_form').target = 'iframe_change_image';
		$('change_image_form').method = 'POST';
		$('change_image_form').enctype = 'multipart/form-data';
		$('change_image_form').action = 'editprofile.php?cmd=changeimage';
		hd = document.createElement('input');
		hd.type = 'hidden';
		hd.name = 'up_file';
		hd.value = $('up_file').getValue();
		$('change_image_form').appendChild(hd);

		var _imageLoaded = function(){
			var r = {//bogus response object
				responseText : '',
				responseXML : null
			};

			try { //
				var doc;
				if(Prototype.Browser.IE){
					doc = frame.contentWindow.document;
				}else {
					doc = (frame.contentDocument || window.frames[id].document);
				}

				if(doc && doc.body){
					r.responseText = doc.body.innerHTML;
				}
				if(doc && doc.XMLDocument){
					r.responseXML = doc.XMLDocument;
				}else {
					r.responseXML = doc;
				}
			}catch(e) {
				// ignore
			}
			var res = null;
			try {
				eval('res = ' + r.responseText);
			}catch(e) {
				// ignore
			}
			ITcraft._loadMask('change_image_form', false);
			if (res) {
				if(res.is_error == false){
					$('profile_user_photo').src = res.new_photo;
					ITcraft.showAlert(res.messages[0]);
				}else{
					ITcraft.showAlert(res.messages[0]);
				}
			}
			setTimeout(function(){$('iframe_change_image').remove();}, 100);
		};
		$('iframe_change_image').observe('load', _imageLoaded);
		ITcraft._loadMask('change_image_form', true);
		$('change_image_form').submit();
	},
	removeImage: function(){
		ITcraft.showConfirm('Are you sure you want to remove your avatar?', 'Confirm', this.sendRemoveImage, this);
	},
//TODO change!
	sendRemoveImage: function(){
		var url = 'editprofile.php?cmd=removephoto';
		var requestData = new Ajax.Request(url,{
		method: 'get',
			onSuccess: function(transport, json) {
				$('profile_user_photo').src = json.new_photo;
				UserAction.showAlert(json.messages[0]);
				UserAction.closeImageWin();
			}
		})
	},
	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: 310,
				height: 235
			},{
				//header: 'Change Email',
				ajax_content: {
					parameters: {
						type: 'change_email_form'
					}
				},
				formConfig: {
					listeners: {
						onSuccess: function(d) {
							$('user_email_box').innerHTML = d.email;
						},
						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 MessageBoard = {
	/*
	 * form_ids:{ send_report_form_inbox: 'send_report_form_inbox',
	 * new_message_form: 'new_message_form' },
	 */
	
	selectedClass: 'message_selected',
	parsedCheckBoxClass: 'class_for_js_parsing',
	sendingString: '',
	count_selected: 0,

	select: function(message_id){
		var tr_message = $('tr_message_'+message_id);
		if (!tr_message) return;
		if(tr_message.className != this.selectedClass){
			tr_message.className = this.selectedClass;
			this.count_selected++;
		}else{
			tr_message.className = 'item_mail';
			this.count_selected--;
		}
	},
	
	resetSelected: function(_delete){
		var checkboxes = document.getElementsByClassName(this.parsedCheckBoxClass);
		this.count_selected = 0;
		if(checkboxes){
			var item = {};
			var len = checkboxes.length;
			var cb2 = Object.clone(checkboxes);
			for(var i= 0; i < len; i++){
				item = cb2[i];
				if(typeof item != 'undefined'){
					var message_id = item.getAttribute('dataindex');
					var tr = $('tr_message_'+message_id);
					tr.className = 'item_mail';
					if(item.checked){
						if(_delete){
							tr.remove();
						}else if($('new_message_'+message_id)){
							$('new_message_'+message_id).className = '';
						}
					}
					item.checked = false;
				}
			}
		}
	},
	/**
	 * Function setup sendingString variable
	 * 
	 * @param bool
	 *            all - if set as true, than function set all selected messages,
	 *            else set only new messages
	 * @access private
	 */
	_setupSendingString: function(all){
		var checkboxes = document.getElementsByClassName(this.parsedCheckBoxClass);
		if(checkboxes) {//if(typeof checkboxes == 'object' || typeof checkboxes == 'function'){
			this.sendingString = '';
			var _new = false;
			var item = {};
			var len  = checkboxes.length;
			for(var i= 0; i < len; i++){
				item = checkboxes[i];
				if(item.getValue() == 'on'){
					var message_id = item.getAttribute('dataindex');
					if(!all){
						if($('new_message_'+message_id).className !=''){
							_new = true;
						}else{
							_new = false;
						}
					}else{
						_new = true;
					}
					if(_new){
						if(this.sendingString == ''){
							this.sendingString = message_id;
						}else{
							this.sendingString += ','+message_id;
						}
					}
				}
			}
		}
	},

	markAsRead: function(){
		this._setupSendingString();
		if(this.sendingString != ''){
			ITcraft.showConfirm('Are you sure you want to make as read selected messages?', 'Confirm',function(){
				ITcraft.request('/ajax/messages.php?cmd=mark_as_read',{
					//method: 'post',
					parameters: {'messages': this.sendingString},
					onSuccess: function(transport, json) {
						this.resetSelected();
					},
					scope: this
				})
			}, this);
		}else{
			ITcraft.showAlert('No selected new messages', 'Notice');
		}
	},

	deleteMessages: function(cmd){
		this._setupSendingString(true);
		if(this.sendingString != ''){
			ITcraft.showConfirm('Are you sure you want to delete selected messages?', 'Confirm',function(){
				ITcraft.request('/ajax/messages.php?cmd='+ (cmd ? cmd : 'delete'),{
					parameters: {'messages': this.sendingString},
					onSuccess: function(r) {
						//reload current page
						history.go(0);
					},
					scope: this
				})
			}, this);
		}else{
			ITcraft.showAlert('No selected messages', 'Notice');
		}
	},
	selectAll: function(a){
		var checkboxes = document.getElementsByClassName(this.parsedCheckBoxClass);

		if(checkboxes) {// == 'object' || typeof checkboxes == 'function'){ // Safari Fix
			this.sendingString = '';
			var _new = false;
			var item = {};
			var len  = checkboxes.length;
			for(var i= 0; i < len; i++){
				item = checkboxes[i];
				var id=item.attributes.getNamedItem('dataindex').value;
				if (item.checked){
					item.checked = false;
					$('tr_message_'+id).className = 'item_mail';
				}
				else{
					item.checked = true;
					$('tr_message_'+id).className = 'message_selected';
				}
			}
		}
	},

	message_wins: {},
	addNewMessage: function(username, without_redirect){
		var k_key = username ? username : '__def__';
		if(!this.message_wins[k_key]){
			this.message_wins[k_key] = ITcraft.ut.getDialog({
				id: 'message_win',
				width: 450,
				height: 370
			},{
//				header: 'Compose Message',
				ajax_content: {
					parameters: {
						type: 'internal_message'
					}
				},
				formConfig: {
					listeners: {
						onSuccess: function(d) {
							if (!this.without_redirect) {
								document.location = '/messages/sent/';
							}
						},
						scope: {
							without_redirect: without_redirect
						}
					}
				}
			});
		}
		this.message_wins[k_key].show();
	},

	reportWins: {},
	sendReport: function(){
		this._setupSendingString(true);
		if(this.sendingString != ''){
			var item_id = this.sendingString;
			if (!this.reportWins[item_id]) {
				this.reportWins[item_id] = new ReportThis({
					item_id: item_id,
					type: 'incomming_messages'
				});
			}
			this.reportWins[item_id].show();
		} else {
			ITcraft.showAlert('No selected messages', 'Notice');
		}
	},
	
	refresh: function(count){
		var url = '/ajax/messages.php?cmd=check_new';
		ITcraft.request(url, {
			parameters: {'count': count},
			onSuccess: function(json, response){
				document.location = '/messages/inbox/';
			},
			scope: this
		});
	},

	resetSearch: function(url){
		if(!url){
			document.location = '/messages/inbox/?grid_cmd=reset';
		}else{
			document.location = url;
		}
	}
};

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();
	}
};