var General = {
	onLoginFormSubmit: function(f) {
		if (!this._loginForm && f) {
			this._loginForm = new ITc.ajaxForm({
				form: f,
				listeners: {
					success: function(form, action) {
						if (action.result['target']) {
							document.location = action.result['target'];
						} else {
							document.location.reload();
						}
					},
					scope: this
				}
			});
		}
		if (!this._loginForm) {
			return false;
		}
		this._loginForm.submit();
		return false;
	},
//TODO move to sepcific page
	onClientRequestInviteSubmit: function(f) {
		if (!this._clientRequestInviteForm && f) {
			this._clientRequestInviteForm = new ITc.ajaxForm({
				form: f,
				listeners: {
					success: function(form, action) {
						$('#after_submit_hide_this').hide();
						$('#close_window_hidden').show();
						$('#client_form_container').html('<p>Glad you\'re interested, we\'ll send you an invite as soon as possible.</p>');
						$('#designer_reg_dialog h3').html('Thank You!');
						return false;
					},
					scope: this
				}
			});
		}
		if (!this._clientRequestInviteForm) {
			return false;
		}
		this._clientRequestInviteForm.submit();
		return false;
	},
//TODO move to sepcific page
	onDesignerRequestInviteSubmit: function(f) {
		if (!this._designerRequestInviteForm && f) {
			this._designerRequestInviteForm = new ITc.ajaxForm({
				form: f,
				listeners: {
					success: function(form, action) {
						$('#after_submit_hide_this').hide();
						$('#close_window_hidden').show();
						$('#designer_request_invite_form').html('<p>Glad you\'re interested, we\'ll send you an invite as soon as possible.</p>');
						$('#designer_reg_dialog h3').html('Thank You!');
					},
					scope: this
				}
			});
		}
		if (!this._designerRequestInviteForm) {
			return false;
		}
		this._designerRequestInviteForm.submit();
		return false;
	},
	
	forgotPassword: {
		dialog: null,
		form: null,
		show: function() {
			if (!this.dialog) {
				var d_cont_id = 'forgot_password_dialog';
				$('body').append('<div style="display:none;"><div id="'+d_cont_id+'"><center>Loading...</center></div></div>');
				var D = ITc.getEl(d_cont_id,true);
				ITc.showMask(D);
				ITc.request('/http/get_forgot_password_dialog.php',{
					parameters:{},
					requestType: 'html',
					onSuccess: function(response, action) {
						ITc.hideMask(D);
						D.html(action.responseText);
					},
					onFail: function(){
						ITc.hideMask(D);
					},
					scope: this
				});
				var self = this;
				this.dialog = ITc.ut.lDialog.create(D,{
					title: 'Forgot Password?',
					width: 400,
					buttons: {
						'Cancel': function(){
							$(this).dialog('close');
						},
						'Get Instructions': function(){
							self.submit();
						}
					}
				});
			} else {
				this.dialog.dialog('open');
			}
		},
		submit: function(){
			if (!this.form) {
				if (!this.dialog) return;
				var form = $('form', this.dialog);
				var formDom = ITc.getEl(form);
				if (!formDom) return;
				
				this.form = new ITc.ajaxForm({
					form: formDom,
					listeners: {
						success: function(form, action) {
							this.dialog.dialog('close');
						},
						scope: this
					}
				});
			}
			this.form.submit();
		}
	},

	onRemoveProject: function(project_id) {
		if (project_id < 1) return false;
		
		ITc.confirm.show('Are you sure want to delete this project?',null,function(){
			ITc.request(
				'/ajax/manage_projects.php',
				{
					parameters : {
						cmd: 'remove',
						project_id: project_id
					},
					onSuccess: function() {
						document.location.reload();
					},
					scope: this
				}
			);
		},this);
	},
	
	initDropdowns: function(){
		$('.dropdown').toggle(
			function() {
				$('.dropdown_options', this).slideDown('fast');
			}, function(e) {
				$('.dropdown_options', this).slideUp('fast');
			}
		);
		$('.dropdown .dropdown_options').bind('click', function(e){
			e.preventDefault();
			if (e.target) {
				document.location = e.target;
			}
		});
	},
	
	initTooltips:function(selector){
		if (!selector) {
			selector = '.tooltip';
		}
		$(selector).qtip({
			position: {
				corner: {
					target: 'topMiddle',
					tooltip: 'bottomMiddle'
				}
			},
			style: {
				border: {
					width: 0,
					radius: 6,
					color: '#000'
				},
				width: {
					min: 120
				},
				fontSize: '1.1em',
				lineHeight: '1.5em',
				backgroundColor: '#000',
				fontFamily: 'Helvetica',
				padding: 10, 
				textAlign: 'center',
				tip: {
					corner: 'bottomMiddle', // We declare our corner within the object using the corner sub-option
					color: '#000',
					size: {
						x: 15,
						y : 8
					}
				},
				name: 'dark'
			},
			hide: 'mouseout'
		});
	}
};

General.stateSelector = {
	chache_states: {},
	onChangeCountry: function(c_selector, state_selector_id, mask_el, back, state_id) {
		var country_id = c_selector.value;
		var state_selector = ITc.getEl(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) {
					ITc.showMask(this.current_mask_el);
				}
				ITc.request('/ajax/get_states_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) {
							ITc.hideMask(this.current_mask_el);
						}
					},
					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;
		} else if (selector.disabled) {
			selector.disabled = false;
		}

		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;
	}
};

General.iu = {};
//need load for clients only
General.iu.project = {
	showLeaveFeedbackConfirm: function(project_id){
		ITc.confirm.show('Do you want to leave feedbacks to designers for the participation in this project right now?',null,function(){
			document.location = '/manage/feedback/waiting/?back_project_id=' + project_id;
		},this,function(){
			document.location.reload();
		});
	},
	
	helpVideo:{
		D:null,
		
		links: {
			step1: 'http://www.youtube.com/v/hWsjTHd9VAI&hl=en_US&fs=1&rel=0',
			step2: 'http://www.youtube.com/v/JX0VSjRDdC0&hl=en_US&fs=1&rel=0',
			step3: 'http://www.youtube.com/v/0Dqev0sAUCY&hl=en_US&fs=1&rel=0',
			step4: 'http://www.youtube.com/v/TKc32jQUqSI&hl=en_US&fs=1&rel=0'
		},
		
		show:function(step){
			if (!this.D){
				if (!this._initDialog(step)) {
					return;
				}
			}
			this.D.dialog('open');
		},
		
		_initDialog:function(step){
			if (!step) {
				step = 'step4';
			}
			if (!this.links[step])return false;
			var link = this.links[step];
			var html = '<div><object width="640" height="385"><param name="movie" value="'+link+'"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="'+link+'" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="false" width="640" height="385"></embed></object>' +
					'<div style="margin-top:10px;"><a class="rbutton red center">Close</a></div>' +
					'</div>';
			
			this.D = $(html).dialog({
				dialogClass:'light-dialog',
				resizable:false,
				modal:true,
				autoOpen:false,
				width:670
			});
			this.D.find('a.rbutton').click(function(){this.D.dialog('close');}.bind(this));
			return true;
		}
		
	},
	
	onCloseConfirm: function(project_id,without_confirm) {
		if (project_id < 1) return;
		ITc.confirm.show('Are you sure you want to close this project?<br /><br />If you decide to close the project, all related workrooms will be closed, all hired designers will receive their rewards, and the project will be blocked in the current state.<br /><br />Before you close the project, make sure you have purchased all the concepts you are interested in.',null,function(){
			ITc.request(
				'/ajax/manage_projects.php',
				{
					parameters: {
						cmd: 'close',
						project_id: project_id
					},
					onSuccess: function() {
						if (without_confirm) {
							document.location.reload();
						} else {
							this.showLeaveFeedbackConfirm(project_id);
						}
					},
					scope: this
				}
			);
		},this);
	},
	
	payDialog:{
		D:null,
		init_content: '<center>Loading...</center>',
		
		show:function(project_id){
			if (project_id < 1) return;
			if (!this.D) {
				this._initDialog();
			}
			
			var d_cont_id = 'project_pay_dialog_'+project_id,
				Cont = $('#'+d_cont_id);
			if (Cont[0]) {
				this._setContent(Cont.html());
			} else {
				this.D.html(this.init_content);
				Cont = $('<div id="'+d_cont_id+'"></div>').appendTo(ITc.getCacheContainer());
				ITc.showMask(this.D);
				
				ITc.request('/http/get_pay_dialog.php',{
					parameters:{
						type: 'pay_for_project',
						project_id: project_id
					},
					requestType: 'html',
					onSuccess: function(response, action) {
						ITc.hideMask(this.D);
						Cont.html(action.responseText);
						this._setContent(Cont.html());
					},
					onFail: function(){
						ITc.hideMask(this.D);
					},
					scope: this
				});
			}
			this.D.dialog('open');
		},
		
		_setContent:function(html){
			this.D.html(html);
		},
		
		_initDialog:function(){
			this.D = ITc.ut.lDialog.create($('<div></div>'),{
				title: 'Pay for Project',
				width: 400,
				buttons: {
					'Cancel': function(){
						$(this).dialog('close');
					},
					'Ok':this._onOkButtonHandler.bind(this)
				}
			});
		},
		
		_onOkButtonHandler:function(){
			switch(this.D.find('.action-el').attr('_daction')){
			case 'pay':
				var project_id = this.D.find('.action-el').attr('_project_id');
				ITc.request(
					'/ajax/manage_projects.php',
					{
						parameters: {
							cmd: 'pay_for_project',
							project_id: project_id
						},
						onSuccess: function() {
							document.location = '/manage/projects/details/'+project_id;
						},
						scope: this
					}
				);
				break;

			case 'add_balance':
				var F = this.D.find('form');
				if (F[0]) {
					F[0].submit();
				} else {
					document.location = '/my-escrow/payment/';
				}
				break;

			default:
				this.D.dialog('close');
				break;
			}
		}
	},
	
	conceptPayDialog:{
		D:null,
		DthankYou:null,
		init_content: '<center>Loading...</center>',
		
		show:function(concept_id){
			if (concept_id < 1) return;
			if (!this.D) {
				this._initDialog();
			}
			
			var d_cont_id = 'concept_pay_dialog_'+concept_id,
				Cont = $('#'+d_cont_id);
			if (Cont[0]) {
				this._setContent(Cont.html());
			} else {
				this.D.html(this.init_content);
				Cont = $('<div id="'+d_cont_id+'"></div>').appendTo(ITc.getCacheContainer());
				ITc.showMask(this.D);
				ITc.request('/http/get_pay_dialog.php',{
					parameters:{
						type: 'pay_for_concept',
						concept_id: concept_id
					},
					requestType: 'html',
					onSuccess: function(response, action) {
						ITc.hideMask(this.D);
						Cont.html(action.responseText);
						this._setContent(Cont.html());
					},
					onFail: function(){
						ITc.hideMask(this.D);
					},
					scope: this
				});
			}
			this.D.dialog('open');
		},
		
		_setContent:function(html){
			this.D.html(html);
			
			var ab = this.D.find('.action-btn');
			
			ab.click(this._onActionButton.bind(this, [ab]));
			this.D.find('.cancel-btn').click(this._onCancelButton.bind(this));
		},
		
		_initDialog:function(){
			this.D = $('<div></div>').dialog({
				dialogClass:'light-dialog',
				resizable:false,
				modal:true,
				autoOpen:false,
				width:450
			});
		},
		
		_onActionButton:function(Button){
			if (!Button) return;
			var type = Button.attr('_act_type');
			switch(type){
			case 'buy':
				ITc.request(
					'/ajax/select_project_winner.php',
					{
						parameters: {
							cmd: 'buy_concept',
							concept_id: Button.attr('_concept_id')
						},
						onSuccess: function(r, action) {
							this._showThankYou(r.redirect_url ? r.redirect_url : '');
						},
						scope: this
					}
				);
				break;
	
			case 'add_balance':
				var F = this.D.find('form');
				if (F[0]) {
					F.submit();
				} else {
					document.location = '/my-escrow/payment/';
				}
				break;
	
			case 'error':
				document.location.reload();
				break;
			}
			this.D.dialog('close');
		},
		
		_onCancelButton:function(){
			this.D.dialog('close');
		},
		
		ty_redirect_url:null,
		_showThankYou:function(redirect_url){
			this.ty_redirect_url = redirect_url;
			if (!this.DthankYou){
				this.DthankYou = $('<div id="pd_thank_you">'+this.init_content+'</div>').appendTo(ITc.getCacheContainer());
				this.DthankYou.dialog({
					dialogClass:'light-dialog',
					resizable:false,
					modal:true,
					autoOpen:false,
					width:350
				});
				ITc.showMask(this.DthankYou);
				ITc.request('/http/get_pay_dialog.php',{
					parameters:{
						type: 'get_pay_for_concept_thank_you'
					},
					requestType: 'html',
					onSuccess: function(response, action) {
						ITc.hideMask(this.DthankYou);
						this.DthankYou.html(action.responseText);
						this.DthankYou.find('.ok-button').click(function(){
							this.DthankYou.dialog('close');
							if (this.ty_redirect_url) {
								document.location = this.ty_redirect_url;
							} else {
								document.location.reload();
							}
						}.bind(this));
					},
					onFail: function(){
						ITc.hideMask(this.DthankYou);
					},
					scope: this
				});
				
			}
			this.DthankYou.dialog('open');
		}
	},
	
	addMoreDesigners:{
		d1: null,
		show: function(project_id) {
			if (project_id < 1) return;
			if (!this.d1) {
				var d_cont_id = 'project_dpay_dialog';
				$('body').append('<div style="display:none;"><div id="'+d_cont_id+'"><center>Loading...</center></div></div>');
				var D = ITc.getEl(d_cont_id,true);

				ITc.showMask(D);
				ITc.request('/http/get_pay_dialog.php',{
					parameters:{
						type: 'pay_for_additional_designer_1',
						project_id: project_id
					},
					requestType: 'html',
					onSuccess: function(response, action) {
						ITc.hideMask(D);
						D.html(action.responseText);
					},
					onFail: function(){
						ITc.hideMask(D);
					},
					scope: this
				});
				
				
				var self = this;
				this.d1 = ITc.ut.lDialog.create(D,{
					title: 'Pay For Additional Designers',
					width: 400,
					buttons: {
						'Cancel': function(){
							$(this).dialog('close');
						},
						'Ok': function(){
							$(this).dialog('close');
							self.showStep2(project_id, $('#price_option_id', this).val());
						}
					}
				});
			}
			this.d1.dialog('open');
		},
		
		showStep2: function(project_id, price_option_id){
			if (project_id < 1 || !price_option_id || price_option_id < 1) {
				return;
			}
			var d_cont_id = 'project_dpay_dialog2';// + project_id + '_' + price_option_id;
			var new_el_content = '<center>Loading...</center>';
			var exists = ITc.getEl(d_cont_id);
			if (exists) {
				exists.innerHTML = new_el_content;
			} else {
				$('body').append('<div style="display:none;"><div id="'+d_cont_id+'">'+new_el_content+'</div></div>');
			}
	//TODO change this
			var D = ITc.getEl(d_cont_id,true);
			ITc.showMask(D);
			ITc.request('/http/get_pay_dialog.php',{
				parameters:{
					type: 'pay_for_additional_designer_2',
					project_id: project_id,
					price_option_id: price_option_id
				},
				requestType: 'html',
				onSuccess: function(response, action) {
					ITc.hideMask(D);
					D.html(action.responseText);
				},
				onFail: function(){
					ITc.hideMask(D);
				},
				scope: this
			});
			
			var self = this;
			ITc.ut.lDialog.create(D,{
				title: 'Pay For Additional Designers',
				width: 400,
				buttons: {
					'Cancel': function(){
						$(this).dialog('close');
					},
					'Ok': function(){
						if (ProjectPayDialogAction && ProjectPayDialogAction.action) {
							var a = ProjectPayDialogAction;
							if (a.action == 'pay') {
								ITc.request(
									'/ajax/manage_projects.php',
									{
										parameters: {
											cmd: 'pay_for_additional_designer',
											project_id: project_id,
											price_option_id: price_option_id
										},
										onSuccess: function() {
											document.location = '/manage/projects/details/'+project_id;
										},
										scope: this
									}
								);
							} else if (a.action == 'add_balance') {
								var F = $('form', this);
								if (F) {
									F.submit();
								} else {
									document.location = '/my-escrow/payment/';
								}
							}
						}
					}
				}
			});
			D.dialog('open');
		}
	}
};

var PomotionalCodeWidget = {
	form_id: 'promotional_codes_widget_form',
	form: null,
	need_reload_on_success: false,
	
	onFormSubmit: function(need_reload_on_success) {
		if (!this.form) {
			var f = ITc.getEl(this.form_id);
			if (!f) return;
			this.need_reload_on_success = need_reload_on_success;
			this.form = new ITc.ajaxForm({form: f,
				listeners: {
					success: function() {
						if (this.need_reload_on_success) {
							document.location.reload();
						} else {
							this.form.form.reset();
						}
					},
					scope: this
				}
			});
		}
		this.form.submit();
	}
};

//need move to sep JS
jQuery(function($) {
	var LB = $('#header_login_box');
	if (LB[0]){
		$('#header_login a').bind('click', function(e) {
			e.preventDefault();
			LB.slideDown('fast');
		});
		
		$('#login_form_hide').bind('click', function(e) {
			e.preventDefault();
			LB.slideUp('fast');
		});
	}
	
	$('.nico.expander[manualAction!=true]').click(function(e) {
		e.preventDefault();
		var El = $(this);
		if (El.hasClass('expanded')){
			$(El.attr('href')).slideUp('fast');
			El.removeClass('expanded');
		} else {
			$(El.attr('href')).slideDown('fast');
			El.addClass('expanded');
		}
	});
});