/*
 * Simple Set Clipboard System
 * Author: Joseph Huckaby
 */
var ZeroClipboard={version:"1.0.4",clients:{},moviePath:'/copy.swf',nextId:1,$:function(thingy){if(typeof(thingy)=='string')thingy=document.getElementById(thingy);if(!thingy.addClass){thingy.hide=function(){this.style.display='none';};thingy.show=function(){this.style.display='';};thingy.addClass=function(name){this.removeClass(name);this.className+=' '+name;};thingy.removeClass=function(name){this.className=this.className.replace(new RegExp("\\s*"+name+"\\s*")," ").replace(/^\s+/,'').replace(/\s+$/,'');};thingy.hasClass=function(name){return!!this.className.match(new RegExp("\\s*"+name+"\\s*"));}}return thingy;},setMoviePath:function(path){this.moviePath=path;},dispatch:function(id,eventName,args){var client=this.clients[id];if(client){client.receiveEvent(eventName,args);}},register:function(id,client){this.clients[id]=client;},getDOMObjectPosition:function(obj){var info={left:0,top:0,width:obj.width?obj.width:obj.offsetWidth,height:obj.height?obj.height:obj.offsetHeight};while(obj){info.left+=obj.offsetLeft;info.top+=obj.offsetTop;obj=obj.offsetParent;}return info;},Client:function(elem){this.handlers={};this.id=ZeroClipboard.nextId++;this.movieId='ZeroClipboardMovie_'+this.id;ZeroClipboard.register(this.id,this);if(elem)this.glue(elem);}};ZeroClipboard.Client.prototype={id:0,ready:false,movie:null,clipText:'',handCursorEnabled:true,cssEffects:true,handlers:null,glue:function(elem){this.domElement=ZeroClipboard.$(elem);var zIndex=99;if(this.domElement.style.zIndex){zIndex=parseInt(this.domElement.style.zIndex)+1;}var box=ZeroClipboard.getDOMObjectPosition(this.domElement);this.div=document.createElement('div');var style=this.div.style;style.position='absolute';style.left=''+box.left+'px';style.top=''+box.top+'px';style.width=''+box.width+'px';style.height=''+box.height+'px';style.zIndex=zIndex;var body=document.getElementsByTagName('body')[0];body.appendChild(this.div);this.div.innerHTML=this.getHTML(box.width,box.height);},getHTML:function(width,height){var html='';var flashvars='id='+this.id+'&width='+width+'&height='+height;if(navigator.userAgent.match(/MSIE/)){var protocol=location.href.match(/^https/i)?'https://':'http://';html+='<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="'+protocol+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="'+width+'" height="'+height+'" id="'+this.movieId+'" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+ZeroClipboard.moviePath+'" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="'+flashvars+'"/><param name="wmode" value="transparent"/></object>';}else{html+='<embed id="'+this.movieId+'" src="'+ZeroClipboard.moviePath+'" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="'+width+'" height="'+height+'" name="'+this.movieId+'" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+flashvars+'" wmode="transparent" />';}return html;},hide:function(){if(this.div){this.div.style.left='-2000px';}},show:function(){this.reposition();},destroy:function(){if(this.domElement&&this.div){this.hide();this.div.innerHTML='';var body=document.getElementsByTagName('body')[0];try{body.removeChild(this.div);}catch(e){;}this.domElement=null;this.div=null;}},reposition:function(elem){if(elem){this.domElement=ZeroClipboard.$(elem);if(!this.domElement)this.hide();}if(this.domElement&&this.div){var box=ZeroClipboard.getDOMObjectPosition(this.domElement);var style=this.div.style;style.left=''+box.left+'px';style.top=''+box.top+'px';}},setText:function(newText){this.clipText=newText;if(this.ready)this.movie.setText(newText);},addEventListener:function(eventName,func){eventName=eventName.toString().toLowerCase().replace(/^on/,'');if(!this.handlers[eventName])this.handlers[eventName]=[];this.handlers[eventName].push(func);},setHandCursor:function(enabled){this.handCursorEnabled=enabled;if(this.ready)this.movie.setHandCursor(enabled);},setCSSEffects:function(enabled){this.cssEffects=!!enabled;},receiveEvent:function(eventName,args){eventName=eventName.toString().toLowerCase().replace(/^on/,'');switch(eventName){case'load':this.movie=document.getElementById(this.movieId);if(!this.movie){var self=this;setTimeout(function(){self.receiveEvent('load',null);},1);return;}if(!this.ready&&navigator.userAgent.match(/Firefox/)&&navigator.userAgent.match(/Windows/)){var self=this;setTimeout(function(){self.receiveEvent('load',null);},100);this.ready=true;return;}this.ready=true;this.movie.setText(this.clipText);this.movie.setHandCursor(this.handCursorEnabled);break;case'mouseover':if(this.domElement&&this.cssEffects){this.domElement.addClass('hover');if(this.recoverActive)this.domElement.addClass('active');}break;case'mouseout':if(this.domElement&&this.cssEffects){this.recoverActive=false;if(this.domElement.hasClass('active')){this.domElement.removeClass('active');this.recoverActive=true;}this.domElement.removeClass('hover');}break;case'mousedown':if(this.domElement&&this.cssEffects){this.domElement.addClass('active');}break;case'mouseup':if(this.domElement&&this.cssEffects){this.domElement.removeClass('active');this.recoverActive=false;}break;}if(this.handlers[eventName]){for(var idx=0,len=this.handlers[eventName].length;idx<len;idx++){var func=this.handlers[eventName][idx];if(typeof(func)=='function'){func(this,args);}else if((typeof(func)=='object')&&(func.length==2)){func[0][func[1]](this,args);}else if(typeof(func)=='string'){window[func](this,args);}}}}};

/*
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){options=options||{};if(value===null){value='';options.expires=-1}var expires='';if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){var date;if(typeof options.expires=='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000))}else{date=options.expires}expires='; expires='+date.toUTCString()}var path=options.path?'; path='+(options.path):'';var domain=options.domain?'; domain='+(options.domain):'';var secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('')}else{var cookieValue=null;if(document.cookie&&document.cookie!=''){var cookies=document.cookie.split(';');for(var i=0;i<cookies.length;i++){var cookie=jQuery.trim(cookies[i]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break}}}return cookieValue}};

/*
 * jQuery Delay
 *
 */
$.fn.delay = function(time, callback){ jQuery.fx.step.delay = function(){}; return this.animate({delay:1}, time, callback); };

/*
 * Scripts
 *
 */
jQuery(function($) {
	
	var Engine = {
		utils : {
			// external links
			links : function(){
				$('a[rel*=external]').attr('target','_blank');
			},
			// mails
			mails : function(){
				$('a[href^=mailto:]').each(function(){
					var mail = $(this).attr('href').replace('mailto:','');
					var replaced = mail.replace('/at/','@');
					$(this).attr('href','mailto:'+replaced);
					if($(this).text() == mail) $(this).text(replaced);
				});
			}
		},
		generator : {
			validate : function(){
				$('#generator form').submit(function(){
					var errors = [];
					
					// podstawowe
					if($('select#f-theme').get(0).selectedIndex == '0') errors[errors.length] = 'Nie wybrano szablonu';
					if($('select#f-expiration').get(0).selectedIndex == '0') errors[errors.length] = 'Nie określono daty wygaśnięcia artykułu';
					if($('select#f-region').get(0).selectedIndex == '0') errors[errors.length] = 'Nie wybrano województwa';
					if($('select#f-city').get(0).selectedIndex === 0 && $('input#f-city-input').val() === '') errors[errors.length] = 'Nie wybrano lub nie wpisano miasta';
					
					// osobowe
					if($('select#f-name').size() > 0 && $('select#f-name').get(0).selectedIndex === 0 && $('input#f-name-input').val() === '') errors[errors.length] = 'Nie wybrano lub nie wpisano imienia bohatera';
					if($('input#f-surname').size() > 0 && $('input#f-surname').val() === '') errors[errors.length] = 'Nie wpisano nazwiska bohatera';
					if($('input#f-age').size() > 0 && $('input#f-age').val() === '') errors[errors.length] = 'Nie określono wieku bohatera';
					if($('input[name="data[sex]"]').size() > 0 && $('input[name="data[sex]"]:checked').size() === 0) errors[errors.length] = 'Nie określono płci bohatera';
					
					// warunki
					if($('input#f-terms:checked').size() === 0) errors[errors.length] = 'Nie wyraziłeś zgody na warunki korzystania z serwisu';
					
					// check
					if(errors.length > 0){
						alert("Wystąpiły błędy w formularzu: \n - " + errors.join("\n - "));
						return false;
					}
				});
			},
			selects : function(){
				$('#generator a.select-input').click(function(){
					var target = $(this).attr('href');
					var current = target.replace("-input","");
					$(current).parent().hide();
					$(target).parent().show();
					return false;
				});
			}
		},
		generated : {
			link : function(){
				var generated = $('#story-url');
				var code = '<p class="copy"><a href="#copy">Kopiuj do schowka</a></p>';
				
				generated.parent().after(code).parent().find('p.copy a').each(function(){
					
					var clip = new ZeroClipboard.Client();
					var item = $(this);
					clip.glue(item[0]);
					clip.setText(generated.val());

	                clip.addEventListener('complete', function(client, text) {
	                   	generated.fadeOut('normal',function(){
							generated.fadeIn('normal');
						});
	                });
					
					item.click(function(){return false;});
					
					return false;
				});
			},
			mails : function(){
				var autoload = $.cookie('mails');
				if(autoload != '' && autoload != null) $('#generated div.send textarea').val(autoload).prev('label').hide();
				
				var ls		= '<p class="mails"><a href="#save" class="save" title="Zapisz">Zapisz</a> <span>|</span> <a href="#load" class="load" title="Wczytaj">Wczytaj</a></p>';
				var tip 	= '<p class="tip">Hej, jeśli generujesz więcej linków i wysyłasz je znajomym ze strony użyj funkcji zapisu i wczytywania adresów, żeby nie musieć wpisywać ich za każdym razem. * - zapis odbywa się przez pliki cookie, więc nie zapisuj na publicznych komputerach (w kafejkach itd.).</p>';
				$('#generated div.send p.sign').before(ls);
				$('#friends').append(tip);
				$('#generated div.send p.mails a').click(function(){
					var mails = $('#generated div.send textarea');
					if($(this).is('.load')){
						var value = $.cookie('mails');
						if(value != '') mails.val(value).prev('label').hide();
					} else {			
						$.cookie('mails', mails.val(), { expires: 365, path: '/'});
						$(this).parent().prepend('<em>Zapisano</em>').find('em').hide().fadeIn(400,function(){
							$(this).fadeOut(400, function(){
								$(this).remove();
							})
						});
					}
					return false;
				});
			},
			labels : function(){
				$('#friends input[type=text], #friends textarea').each(function(){
					if($(this).val() == '') $(this).prev('label').show()
				}).focus(function(){
					$(this).prev('label').hide();
				}).blur(function(){
					if($(this).val() == '') $(this).prev('label').show()
				});
			},
			validate : function(){
				$('#friends').submit(function(){
					var form = $(this);
					var errors = [];
					if($('#f-friends').val() == '') errors[errors.length] = 'Nie podałeś adresu email znajomego';
					if($('#f-sign').val() == '') errors[errors.length] = 'Nie podpisałeś się';
					if($('#f-email').val() == '') errors[errors.length] = 'Nie podałeś swojego adresu email';
					
					// check
					if(errors.length > 0){
						alert("Wystąpiły błędy w formularzu: \n - " + errors.join("\n - "));
						return false;
					} else {
						/*form.append('<p class="loading">Wysyłam...</p>').find('p.loading').css('opacity',0).animate({opacity: 0.8},600,function(){
							form.find('textarea,input[type=text]').val('');
							$(this).fadeOut(600,function(){
								$(this).remove();
								form.find('label').show();
								form.find('p.emails').before('<p class="message-a">Powiadomienia wysłano, dziękujemy!</p>').prev('p.message-a').delay(3500,function(){
									$(this).fadeOut(600,function(){
										$(this).remove();
									});
								});
							});
						});
						return false;*/
					}
				});
			}
		},
		information : {
			tabs : function(){
				iroot = $('#information');
				
				var url = new String(document.location);
				if(url.indexOf("#") != -1){
					var target = url.substr(url.indexOf('#'));
					var current = $(target);
					iroot.find('div.secondary div.box-a ul.a li a[href$='+target+']').addClass('active');
				} else {
					var current = iroot.find('div.primary div.box-a:first');
					iroot.find('div.secondary div.box-a ul.a li a:first').addClass('active');
				}
				$(current).fadeIn(500);
				
				iroot.find('div.secondary div.box-a ul.a').click(function(e){
					var clicked = $(e.target);
					//e.preventDefault();
					if(clicked.is('a') && !clicked.is('.active') && iroot.find('div.primary div.box-a:animated').size() == 0){
						iroot.find('div.secondary div.box-a ul.a li a').removeClass('active');
						clicked.addClass('active');
						iitem = $(clicked.attr('href').substr(clicked.attr('href').indexOf('#')));
						iroot.find('div.primary div.box-a:visible').fadeOut(500,function(){
							iitem.fadeIn(500);
						});
					}
				});
			}
		}
	};

	Engine.utils.links();
	Engine.utils.mails();
	Engine.generator.selects();
	Engine.generator.validate();
	Engine.generated.link();
	Engine.generated.mails();
	Engine.generated.labels();
	Engine.generated.validate();
	Engine.information.tabs();
	
});

document.write('<link rel="stylesheet" type="text/css" media="screen" href="/styles/javascript.css" />');