/**
 * @author keemor
 */
var Core = {
	init : function() {		
		this.el = null;		
		$$('a','.submit').invoke('observe','click',function(e){ Core.el = this; });		
		this.contactTypes = [];		
		//this.setContactTypes = this.setContactTypes.bind(this); 
		this.setSubmenu();
		this.menuHandler();					
		this.registerAjaxResponders();		
		this.setContactTypes();
						
		if ($('help-href')) {
			$('help-href').observe('click', function(e){
				e.stop();
				Overlay.On('help-system', ['help-close']);
			});
		}
		
		this.contactsAmount = $('contacts-amount');			
		if (this.contactsAmount) {
			this.amount;
			this.rNum;
			setInterval('Core.setContactsAmount()',3000);	
		}

		$('a-lang').observe('mouseover',function(e) {			
			$('lang-container').show();
		}).observe('mouseout',function(e) {			
			$('lang-container').hide();
		})
		$('lang-container').observe('mouseover',function(e) {			
			$('lang-container').show();
		}).observe('mouseout',function(e) {			
			$('lang-container').hide();
		})
		
		if ($('recaptcha_response_field')) {
			$('recaptcha_response_field').tabIndex = 0;
		}								
	},
	registerAjaxResponders: function() {
		Ajax.Responders.register({
			onCreate: function() { 	
				if (Core.el) { Core.el.setStyle({cursor: 'wait'}); $$('BODY')[0].setStyle({cursor: 'wait'});
				}},
			onComplete: function(request,transport) {
				if (0 == Ajax.activeRequestCount) { 
					if (Core.el) { Core.el.setStyle({cursor: 'pointer'}); Core.el = null; $$('BODY')[0].setStyle({cursor: 'auto'});}	
					}
			if (401 == transport.status) { location.reload(true); } 
			if (500 == transport.status) { alert('Processing error occurred (we messed up).\n\nPlease try again and let us know if this is a repeating problem.'); }
		}})		
	},
	setSubmenu: function()  {		
		var topGecko  = '2.55em';
		var topIE 	  = '2.7em';
		var topOpera  = '2.6em';
		var topWebKit = '2.5em';
		var top;	
		if (Prototype.Browser.Gecko) top = topGecko;
		if (Prototype.Browser.IE) top = topIE;
		if (Prototype.Browser.Opera) top = topOpera;
		if (Prototype.Browser.WebKit) top = topWebKit;
		$$('.submenu').invoke('setStyle',{top:top});
	},
	menuHandler: function() {
		$$('a.menu-a').invoke('observe','click',function(e){
		var el = e.element();
		if (el.hasClassName('menu-a')) {
			var id = el.readAttribute('id');		
			e.stop();							
			if ($('link-' + id).hasClassName('open')) {				
				$('link-' + id).removeClassName('open').setStyle({zIndex:0});
				$('sub' + id).hide();
				el.setStyle({
					backgroundPosition: 'right 2px'
				})
			} else {
				$$('.menu-link').invoke('removeClassName','open').invoke('setStyle',{zIndex:0});												
				$$('.submenu').invoke('hide');									
				$$('a.menu-a').invoke('setStyle',{
					backgroundPosition: 'right 2px'
				})
				$('link-' + id).addClassName('open').setStyle({zIndex:20});
				$('sub' + id).show();									
				el.setStyle({
					backgroundPosition: 'right -54px'
				})	
			}									
			}	
		})
		.invoke('observe','mouseover',function(e) {
			var el = e.element(); 
			if (el.hasClassName('menu-a')) {
				var id = el.readAttribute('id');
				if (!$('link-' + id).hasClassName('open')) {
					el.setStyle({
						backgroundPosition: 'right -26px'
					})
				}
			}	
		})
		.invoke('observe','mouseout',function(e){
			var el = e.element();
			if (el.hasClassName('menu-a')) {
				var id = el.readAttribute('id');
				if (!$('link-' + id).hasClassName('open')) {
					el.setStyle({
						backgroundPosition: 'right 2px'
					})
				}
			}	
		})
		.invoke('observe','focus',function(e){this.blur();})
		document.observe('click',function(e) {
				$$('.menu-link').invoke('removeClassName','open').invoke('setStyle',{zIndex:0});			
				$$('.submenu').invoke('hide');				
				$$('a.menu-a').invoke('setStyle',{
					backgroundPosition: 'right 2px'
				})
		});
	},
	setContactTypes: function() {
		this.contactTypes['ims_json'] = [["Jabber", "j"], ["Google Talk", "t"], ["ICQ", "i"], ["Yahoo!", "y"], ["MSN", "m"], ["Skype", "s"], ["Gadu-Gadu", "g"], ["Other", "o"]];
		this.contactTypes['numbers'] = new Hash; 
		this.contactTypes['emails'] = new Hash; 
		this.contactTypes['ims'] = new Hash; 
		this.contactTypes['addresses'] = new Hash; 
			
		this.contactTypes['numbers'].set('h','Home');
		this.contactTypes['numbers'].set('w','Work');
		this.contactTypes['numbers'].set('m','Mobile');
		this.contactTypes['numbers'].set('f','Fax');
		this.contactTypes['numbers'].set('p','Pager');
		this.contactTypes['numbers'].set('o','Other');
		
		this.contactTypes['emails'].set('p','Private');				
		this.contactTypes['emails'].set('w','Work');				
		this.contactTypes['emails'].set('o','Other');			
		
		this.contactTypes['addresses'].set('p','Private');				
		this.contactTypes['addresses'].set('w','Work');		
		this.contactTypes['addresses'].set('o','Other');			
		
		this.contactTypes['ims_json'].each(function(v){		
			this.contactTypes['ims'].set(v[1],v[0]);				
		}.bind(this));
	},
	lightChanged: function (el) {
		el.addClassName('update').morph('white',{duration: 2});
		window.setTimeout(function() { el.removeClassName('update').removeClassName('white'); }, 2000);
		return null;
	},
	readCookie: function (name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length,c.length));
		}
		return null;
	},	
	setCookie: function (key,value){
		var date = new Date();
		date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000));
		var expires = "; expires=" + date.toGMTString();
		document.cookie = key+"=" + value + expires + "; path=/";		
	},	
	rshListener:  function(newLocation, historyData) {
		if (historyData) {					
			if (historyData[3] != 'empty') {
				Contact.data = historyData[0];
				Group.group_id = historyData[1];
				Contact.info = historyData[2];
				Contact.letter = historyData[3];
				Contact.filter = historyData[4];
				Contact.notLabeled = historyData[5];								
				Group.show();
				Contact.show();
			} else {						
				Contact.contactData = historyData[1];
				Contact.contactInfo = historyData[2];
				Contact.setIdContact(historyData[0]);								
				Contact.showEditForm();
			}
		}
	},
	setMessage: function(msg) {		
		$('message-global').update(msg).show();
		Effect.Fade.delay(3, 'message-global',{ duration: 2.0 });
	},
	setContactsAmount: function() {
		this.rNum=Math.floor(Math.random()*101);
		this.amount = parseInt(this.contactsAmount.innerHTML);								
		if (this.rNum % 2) {
			this.amount += this.rNum;	
		} else {
			this.amount -= this.rNum;			
		}
		this.contactsAmount.update(this.amount);	
	}
}
document.observe('dom:loaded', Core.init.bind(Core));

var Overlay = {	
	init: function() {				
		this.overlayDiv = $('overlay'); 
		this.html = $('contails-html'); 
		this.body = $('contails-body');
		this.docViewHeight = document.viewport.getHeight();
		//this.height = (document.outerHeight) ? document.outerHeight : 2000+'px';				 
		this.height = 2000+'px';
	},
	On: function(element, closeElements){							
		this.element = $(element);		
		this.closeElements = closeElements;
		var top = ((this.docViewHeight - this.element.getHeight())/2);		
		top = (top > 0) ? top : 0;		  		
		this.element.addClassName('overlay-content').setStyle({top : top+'px'}).show();						
		this.html.setStyle({overflowY: 'hidden'}).scrollTo();		
		this.body.setStyle({overflowY: 'hidden'});										  				
		this.overlayDiv.setStyle({height : this.height}).show();
		
		this.overlayDiv.observe('click',function(e){
			Overlay.Off();
		});
		if (Object.isArray(closeElements)) {			
			closeElements.each(function(closeEl) {
				$(closeEl).stopObserving();	
				$(closeEl).observe('click',function(e){					
					e.stop();
					Overlay.Off();									
				})
			})			
		}
		document.observe('keyup', function(e){	
			if (e.keyCode == Event.KEY_ESC) {
				Overlay.Off();
			}
		});		 				
	}, 
	Off: function(){
		this.element.removeClassName('overlay-content').hide();							
		if (Prototype.Browser.IE) {
			this.html.setStyle({overflowY: 'scroll'});			
		} else {
			this.html.setStyle({overflowY: 'auto'});
			this.body.setStyle({overflowY: 'scroll'});
		}		
		this.overlayDiv.stopObserving().hide();		
	}	
}
document.observe('dom:loaded', Overlay.init.bind(Overlay));


var PopupMG = {
	init: function(){
		this.id_friend;
		this.id_contact;		
		this.defaultPhoto = '/imgs/avatar_86.jpg';
		$$('a.contact-popup').invoke('stopObserving').invoke('observe','click',this.popupOpen.bind(this));
		document.observe('click',this.popupClose);
	},
	templates: {
		popupInner: new Template('<b class="ut"><span></span><b></b></b>' +
			'<div class="tip"></div>' +
			'<div class="content"><div class="content-inner"><h4><a href="/contacts/browse.html?id_contact=#{id_contact}">#{first_name} #{last_name}</a> <a href="#" class="contact-popup-close"></a></h4>' +
			'<div class="image"><img src="#{photo_url}"/></div>' +
			'<ul><li><strong id="popup-email-li">E-mail:</strong> #{email}</li>' +
			'<li id="popup-phone-li"><strong>Phone:</strong> #{number}</li>' +
			'<li class="more"><a href="/contacts/browse.html?id_contact=#{id_contact}">View contact&#146;s details</a></li></ul>' + 
			'</div></div><b class="ub"><span></span><b></b></b>'),			
		popupInnerEmpty: '<b class="ut"><span></span><b></b></b>' +			
			'<div class="tip"></div>' +
			'<div class="content"><div class="content-inner"><h4>Contact doesn\'t exist <a href="#" class="contact-popup-close"></a></h4>' +
			'<ul><li>Contact doesn\'t exist</li></ul>' +						 
			'</div></div><b class="ub"><span></span><b></b></b>'
	},
	popupOpen: function(e) {
		this.popupClose(e);
		var a = e.element();
		if (a.hasClassName('type-friend')) {
			this.id_friend = a.readAttribute('id');
			this.id_contact = null;			
		} else {
			this.id_friend = null;
			this.id_contact = a.readAttribute('id');			
		}
		a.wrap('div',{ 'class': 'contact-popup-outer' });
		a.insert({
			after: new Element('div', {
				'class': 'contact-popup-inner'
			})
		});												
		this.xhrFetchData();														
		e.stop();						
	},
	popupClose: function(e) {
		if (e && e.element().hasClassName('contact-popup-close')) e.stop();
		$$('.contact-popup-outer').each(function(div){		
			div.insert({after : div.down('a')});
			div.remove();			
		});	
	},
	xhrFetchData: function() {
		new Ajax.Request("/xhr/contact/fetch_short_contact?lang=pl",{			
			parameters: {								  		
				id_friend: this.id_friend,
				id_contact: this.id_contact
			},
			onSuccess: function(transport){				
				var Response = transport.responseJSON;	
				if (Response.info.status) {
					Response.data['id_friend'] = this.id_friend;
					if (!Response.data.avatar_info) {
						Response.data['photo_url'] = this.defaultPhoto;
					} else {
						Response.data['photo_url'] = Response.data['avatar_info']['url']+Response.data['avatar_info']['medium']+'?'+Response.data['avatar_info']['last_update']; 
					}
					$$('.contact-popup-inner')[0].update(this.templates.popupInner.evaluate(Response.data));
					if (!Response.data.number) {
						$('popup-phone-li').hide();	
					}
					if (!Response.data.email) {
						$('popup-email-li').hide();	
					}										
					$$('a.contact-popup-close').invoke('observe', 'click', this.popupClose);
				} else {
					$$('.contact-popup-inner')[0].update(this.templates.popupInnerEmpty);
				}
			}.bind(this)	
		})						
	}			
}				
document.observe('dom:loaded', PopupMG.init.bind(PopupMG));

//function regAction(e){
//	el = e.element();
//		
//	var cookie;
//	cookie = readCookie('action');				
//	if (cookie && cookie.isJSON()) {	
//		cookie = cookie.evalJSON(true);		
//	} else {						
//		cookie = new Array();
//	}	
//	el = e.element();		
//	var value = new Hash;	
//	value.set('t', el.tagName);
//	if (el.readAttribute('id')) value.set('i', el.readAttribute('id'));
//	if (el.readAttribute('class')) value.set('c', el.readAttribute('class'));	
//	if (el.tagName == 'INPUT') {
//		if (el.value) value.set('v', el.value);
//	} else {
//		if (el.readAttribute('href')) value.set('f', el.readAttribute('href'));
//		if (el.innerHTML) value.set('r', el.innerHTML);
//	}	
//	var currentDate = new Date();			
//	value.set('s', Math.round( currentDate.getTime()  / 1000));
//	if (window.location.pathname) value.set('p',window.location.pathname);
//	if (window.location.hash) value.set('h',window.location.hash);
//	if (window.location.search) value.set('m',window.location.search);
//	if (Object.isArray(cookie)) {	
//		if (cookie.size() > 4) {
//			new Ajax.Request("xhr_click_save",{
//				onSuccess: function(transport) { return }
//			})
//		}
//		cookie.push(value);		
//	}		
//	document.cookie = 'action=' + escape(cookie.toJSON()) + '; path=/';
//	
//}



var $l = {};
$l.no_contacts = 'No contacts';
$l.trash = 'Trash';	
$l.trashIsEmpty = 'Trash is empty';
$l.notLabeled = 'Contacts <span id=label-icon-header class=label-icon>without label</span> (<a href=# id=contacts-show-all>show all</a>)';		
$l.allLabeled = 'All contacts have <span id=label-icon-header class=label-icon>labels</span> (<a href=# id=contacts-show-all>show all</a>)';
$l.contactsWithoutAccount = 'contacts without account';
$l.contactsWithAccount = 'suggested connections';
$l.friends = 'existing connections';
$l.last_modified = 'last modified';	
$l.contactsLabeled = 'Contacts labeled <span id=label-icon-header class=label-icon>#{groupName}</span> (<a href=# id=contacts-show-all>show all</a>)';
$l.noContactsLabeled = 'No contacts labeled <span id=label-icon-header class=label-icon>#{groupName}</span> (<a href=# id=contacts-show-all>show all</a>)';
$l.andFilteredBy = ' <span>+</span> filtered by <span>#{filterName}</span>';
$l.filteredBy = 'Contacts filtered by <span>#{filterName}</span>';
$l.cancelFilter = 'cancel filter';
$l.letter = 'letter';
$l.unassignLabel = 'unassign label';
$l.addNewLabelFirst = 'Add new label first';
$l.checkAll = 'Check all';
$l.uncheckAll = 'Uncheck all';
$l.close = 'Close';	
$l.save = 'Save';	
$l.or = 'or';	
$l.cancel = 'Cancel';	
$l.connectWithFriends = 'Connect with friends';	
$l.and = 'and';	
$l.infoCloud1 = 'This contact seems similar to following contacts on your list:';
$l.mergeContacts = 'Merge contacts';
$l.connect = 'connect';	
$l.loading = 'loading...';
$l.invitationSent = 'Invitation sent';	
$l.ago = 'ago';
$l.sendAgain = 'send again';	
$l.connectWith = 'Connect with';
$l.invite = 'Invite';	
$l.empty = 'empty';	 		
$l.syncSummary = 'You have now <span>#{new_suggestions}</span> new <a href="/contacts/merge.html">merge suggestions</a>.';
$l.syncStatusParagraph1 = 'Contacts synchronized on <span>#{date}</span>'; 
$l.syncStatusLi1 = 'new'; 
$l.syncStatusLi2 = 'removed'; 
$l.syncStatusLi3 = 'updated'; 
$l.syncInProgress = 'Synchronization with <strong>#{brand_name} #{model}</strong> in progress...';
$l.syncComplete = 'Synchronization complete!';
$l.syncOK = 'It is OK';
$l.syncNotOK  = 'It&#146;s not OK';
$l.get_sync_status_xhr = "/xhr/mobiles/phone/get_sync_status?lang=pl";
$l.get_sync_result_xhr = "/xhr/mobiles/phone/get_sync_result?lang=pl";
$l.set_sync_status_xhr = "/xhr/mobiles/phone/set_sync_velvet_status?lang=pl";
$l.get_models_xhr = "/xhr/mobiles/wizard/get_models?lang=pl"; 


 

function Contails() {	

if ($('login-user-form')) {		
	$('login-user-form').observe('submit', function(e){
		if (!$F('lemail') || !$F('lpassword')) {
			$('lemail').activate();
			e.stop();
			return;
		}		
		$('login-user-submit').disable();		
	});
}

if ($('subscribeuser-form')) {
	$('subscribeuser-email').activate();
	$('subscribeuser-form').observe('submit', function(e){	
		if (!$F('subscribeuser-email')) {
			$('subscribeuser-email').activate();
			e.stop();
			return;
		}		
		$('subscribeuser-submit').disable();		
	});
}

if ($('rememberpassword-form')) {
	$('rememberpassword-email').activate();
	$('rememberpassword-form').observe('submit', function(e){	
		if (!$F('rememberpassword-email')) {
			$('rememberpassword-email').activate();
			e.stop();
			return;
		}		
		$('rememberpassword-submit').disable();		
	});
}

if ($('confirmpassword-form')) {
	$('actpassword').activate();
	$('confirmpassword-form').observe('submit', function(e){	
		if (!$F('actpassword')) {
			$('actpassword').activate();
			e.stop();
			return;
		}		
		$('confirmpassword-submit').disable();		
	});
}

if ($('changepassword-form')) {
	$('actualpassword').activate();
	$('changepassword-form').observe('submit', function(e){	
		if (!$F('newpassword') || !$F('confirmpassword')) {			
			e.stop();
			return;
		}		
		$('changepassword-submit').disable();		
	});
}

if ($('resetpassword-form')) {
	$('password').activate();
	$('resetpassword-form').observe('submit', function(e){	
		if (!$F('password') || !$F('confirmpassword')) {			
			e.stop();
			return;
		}		
		$('changepassword-submit').disable();		
	});
}



}	
