/*
 * Plura P Jquery Plugin Collection 
 * 
 * Copyright (c) 2009 Plura
 *
 * Date: 2009-07-24 12:30:50 (Fri, 24 July 2009)
 * Revision: 6246
 */
(function($) {

	//gets the css value. used mainly for hover, etc pseudo selectors that cannot be retireved via javascript
	//seems to throw an error in FF 
	$.fn.pCSS		= function(property){
		
		var st		= "";

		//Check every stylesheets loaded into browser and every CSS rules
		for(i in document.styleSheets){
			var rules = document.styleSheets[i];
			
			for (j in rules.cssRules){
				var css = new String(rules.cssRules[j].cssText);
				
				if(new RegExp($(this).selector, 'i').test(css) && new RegExp(property+"\s*\:\s*([^;\}]*)","i").test(css))	
					st = rules.cssRules[j].cssText;
			}
		}

		//revalidate as String
		st = new String(st);
 
		var val = st.match(property+"\s*\:\s*([^;\}]*)","i");
		if(val) st = new String(val[1]);

		if(st=="" || st=="undefined") st=false

		return st;
	}
  
  
  

   /**
	* pForm is used for AJAX form submission, value checking and file uploading
	* ATTENTION: 	making a deep $.extend [ie. $.extend(true, {}, $.fn.pForm.defaults, options)] will break some deep level
	*				objects like option.check.rules.exp regular expression [turned them into object, rendering them useless]
	*				p.reg was changed to accept strings in order to bypass pForms' $extend RegExs 'destroyed' as objects 
	* 
	* @param	alert				template string for alert
	* @param	check				array of form objects to be validated
	*			@param	id			css selector string for jQuery identifier
	*			@param	reg			if null only the .val() is checked
	*			@param	alert		alert string
	* @param	init				function triggered after after successfull submit
	* @param	end					function triggered after form processing
	* @param	path				form process script path string
	* @param	replace				replaces file type inputs with an swf upload
	* @param	reset				resets form after successfull processing
	* @param	upload				upload replacement options
	*			@param	label		swf upload button label string
	* 			@param	flash		SWFObject parameters [ie. {flashvars:{}, params:{}]]
	*/
	$.fn.pForm	= function(options, callback){
		var opts 			= $.extend(true, {}, $.fn.pForm.defaults, options);	
		var obj				= this;
		$.fn.pForm.count	= $.fn.pForm.count == undefined? 0 : $.fn.pForm.count;

		if(opts.replace && $(this).find('input[type=file]').length){			//replace file input with flash	
			$.fn.pForm.replace($(this).find('input[type=file]'), opts.upload);		
		}

		$(this).submit(function(){
			if(opts.check){														//if validation check option available
				for(i in opts.check){
					var c		= opts.check[i];
					var rules	= c.rules?($.isArray(c.rules)? c.rules : [c.rules]) : [{exp:false, alert:c.alert? c.alert : opts.alert.split('%').join($(this).find(c.id).attr('name'))}];
					for(n in rules){
						var target = $.p.test([/\./,/#/], c.id)? $(this).find(c.id) : $(this).find('*[name='+c.id+']')
						if(rules[n].exp){ if(!$.p.test(rules[n].exp, target.val()))	{ alert(rules[n].alert); return false;	}}	
						else			{ if(target.val() == "")					{ alert(rules[n].alert); return false;	}}
					}
				}	
			}

			$.post(opts.path, $(this).serialize(), function(data){ 
				if(opts.end) 	opts.end(obj, data);
				if(opts.reset)	obj.each(function(){ this.reset(); });	//reset form if reset option is true
			});
			if(opts.init) opts.init($(this));
			
			return false;
		});
		
		$.fn.pForm.count = ++$.fn.pForm.count;
	}
	
   /**
	* replaces every input[type=file] with a flash object
	* @param	obj			input[type=file] DOM form object
	* @param	options		replacement options parameters
	*/	
	$.fn.pForm.replace	= function(obj, options){
		obj.each(function(i){
			var path	= ($('script[src$="p.js"]').attr('src')).replace(/p\.js$/, 'p.js.FormFile.swf');
			var w		= $(this).width();
			var h		= $(this).height();
			var vars	= $.extend(true, {}, options.vars, {
				id:			'pForm'+$.fn.pForm.count+'_file'+i,
				process:	($('script[src$="p.js"]').attr('src')).replace(/p\.js$/, 'p.js.FormFile.php')
			});
			
			//add replacement div, hidden input for file info storage and swf div holder
			$('<div class="file" id="'+vars.id+'"><div id="'+vars.id+'_flash'+'"></div></div>').replaceAll($(this));
			$('#'+vars.id).prepend('<input type="hidden" name="'+$(this).attr('name')+'" />');
			swfobject.embedSWF(path, $('#'+vars.id).attr('id')+'_flash', w, h, options.version, null, vars, options.params);
		});
	}
	
   /**
	* adds the new uploaded file controls. includes a delete button
	* @param	json		json string received from p.js.Form.Upload.swf after successfully completed an upload 
	*/
	$.fn.pForm.file		= function(json){
		var o	= eval("new Object("+json+")");
		var b	= $('<label>'+o.name+'<input type="button" value="'+'Delete'+'" /></label>').appendTo('#'+o.id);
		b.data('json', o).hide().fadeIn('slow')
   	     .find('input[type=button]').click(function(){
			$.getJSON(o.process, {action:'delete', path:o.path, file:o.file}, function(data){
				if(data.success) 
					b.fadeOut('fast', function(){ $(this).remove(); $.fn.pForm.refresh($('#'+o.id)); });
				else
					alert('error');
			})																		   
		})
		  
		$.fn.pForm.refresh($('#'+o.id));
	}
	
   /**
	* Refreshes hidden input with uploaded file[s] [uploaded name & name]
	*/
	$.fn.pForm.refresh	= function(fileobj){
		var f = [];
		fileobj.find('label').each(function(i){ f[i] = $(this).data('json').name+";"+$(this).data('json').file; });
		fileobj.find('input[type="hidden"]').val(f.join('|'));
	}

	$.fn.pForm.defaults	= {alert:'Please correctly fill the % field. Thank you', check:false, end:false, init:false, path:null, replace:true, reset:true, upload:{label:'Delete', version:'9.0.28.0', vars:{label:'Upload'}, params:{allowscriptaccess:'always', menu:'false', wmode:'transparent'}}};



   /**
	* refreshes html content. If time option is not set to null, it triggers an interval.
	* important: ie7/ie6 cannot handle parameters in setInterval. It's necessary to store in the 'first 
	* round' the options in a var, 'prefresh_opts' and on the following iterations (obj.data('prefresh_n')>0)
	* get that value. fuck ie6/ie7
	*
	* @param	time
	* @param	path
	* @param	data		
	* @param	fade		boolean value enable/disable fade transition
	* @param	speed		int value indicating fade speed
	* @param	change		function triggered on change
	*/
	$.fn.pRefresh	= function(options){
		var obj	 	= this;
		var opts 	= $.extend({}, $.fn.pRefresh.defaults, options);
		if(obj.data('prefresh_n') == undefined) 				obj.data('prefresh_n', 0);
		if(obj.data('prefresh_opts') == undefined)				obj.data('prefresh_opts', opts);	//4 ie6|ie7
		if(obj.data('prefresh_n')>0 && options == undefined)	opts = obj.data('prefresh_opts');	//4 ie6|ie7

		var show	= function(obj, opts, data){
			obj.each(function(){ 
				if(opts.fade){obj.fadeOut(opts.speed, function(){ obj.html(data).fadeIn(opts.speed);	if(opts.change) opts.change(obj); }); }
				else		 {obj.html(data); 															if(opts.change) opts.change(obj); }
			});

			if(obj.timer == undefined || obj.timer == null){
				obj.timer = setInterval( function(o){ obj.pRefresh(o); }, opts.time, opts);	
			}
		}

		if(opts.path)		{ $.post(opts.path, null, function(data){ show(obj, opts, data); });	} 
		else if(opts.data)	{
			var n = obj.data('prefresh_n');
			show(obj, opts, opts.data[n%opts.data.length]); 
			obj.data('prefresh_n', n+1);
		}
	}
	
	$.fn.pRefresh.defaults	= {time:10000, path:false, data:false, fade:true, speed:'slow', change:false};
	
	
	
	$.fn.pResize	= function(options){
		var opts 	= $.extend({}, $.fn.pResize.defaults, options);		

		var resize	= function(w0, h0, nw, nh){
			if(nw != undefined && nh == undefined)	{ var w = nw; 		var h = nw*h0/w0; 	} 
			else if(nw == null && nh != undefined)	{ var w = nh*w0/h0;	var h = nh;			}	
			return {width:w, height:h};
		}
		
		return this.each(function(){ 
			var dims = resize($(this).width(), $(this).height(), opts.width, opts.height);
			$(this).width(dims.width).height(dims.height);
		});
	}
	
	$.fn.pResize.defaults	= {width:null, height:null};



  	//adds an accordion effect to a list strcuture
	$.fn.pFXAccordion	= function(options){
		
		var o = $.extend({}, $.fn.pFXAccordion.defaults, options);
		
 		return this.each(function() {
			$(this).children('ul').hide();
			$(this).children('a').click(function(){
				$(this).parent().children('ul').toggle(o.easing);
				return false;
			});
		});
	};	
	
	$.fn.pFXAccordion.defaults = {easing:'slow'};
	
	
	
   /**
	* adds corners div structure
	* @param	single		boolean value
	*/
	$.fn.pFXCorners		= function(options){
		
		var o = $.extend({}, $.fn.pFXCorners.defaults, options);		
		
		$(this).each(function(i){
 
			if(!o.single){
				$(this).wrap('<div class="pwp_corners_m"><div class="bd"><div class="c"><div class="s"></div></div></div></div>')
					   .prepend('<div class="hd"><div class="c"></div></div>')
					   .append('<div class="ft"><div class="c"></div></div>');
			} else {
				$(this).wrap('<div class="pwp_corners_s"><div class="content img"></div></div>')
					   .before('<div class="t img"></div>')
					   .parent().after('<div class="b img"><div class="img"></div></div>');
			}
			
			$(this).parent().parent().attr('id', 'pwp_corners_'+i);
		});
	}
		
	$.fn.pFXCorners.defaults = {single:true};		



   /**
	* useful to switch content betwn a link menu [ie. bullet list menu]
	* and related, content holder divs
	*/
	var p_tab_selected;
	var p_tab_selected_nav;

	$.fn.pTabs		= function(options){
		
		var o = $.extend({}, $.fn.pTabs.defaults, options);
		
		return $(this).each(function(){
			var c = $($(this).attr('href'));
			$(this).click(function(){
				if(p_tab_selected == undefined || p_tab_selected.attr('id') != c.attr('id')){
					if(p_tab_selected){
						p_tab_selected.hide(o.speed);
						p_tab_selected_nav.css(o.inactive);
					}
					p_tab_selected 		= c;
					p_tab_selected_nav	= $(this);
					p_tab_selected.show(o.speed, o.show);
					p_tab_selected_nav.css(o.active);
				}
				
				return false;
			});
			
			if(o.hide) c.hide();
		})
	}
	
	$.fn.pTabs.defaults = {hide:false, inactive:{'font-weight':'normal'}, active:{'font-weight':'bold'}, speed:'slow', show:null};
	//$.fn.pTabs_style = function(status){}



	$.fn.pBookmark = function(){
		// don't overwrite the rel attrib if already set  
	    if(window.opera)			{ if($(this).attr("rel") != ""){ $(this).attr("rel","sidebar"); }}  

        var url		= document.location.href;  
        var title	= document.title;  
        
		if(window.sidebar.addPanel) { window.sidebar.addPanel(title, url,"");  	// Mozilla Firefox Bookmark  (evaluates window.sidebar.addPanel instead of window.sidebar because of possible conflicts with divs with the same name
		} else if(window.external)	{ window.external.AddFavorite( url, title);	// IE Favorite  
		} else if(window.opera) 	{ return false;								// Opera 7+  do nothing - the rel="sidebar" should do the trick   
		} else 						{ 											// for Safari, Konq etc - browsers who do not support bookmarking scripts (that i could find anyway)  
			alert('Unfortunately, this browser does not support the requested action,' + ' please bookmark this page manually.');  
        }  
	}



	jQuery.p = {
		
		CONST: {
			REGEX_EMAIL: 		/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/
		},
		
		//gets var from a URI like query string:  &var1=value&var2=value&var3=value3
		query:	function(varname, string){
			var reg		= new RegExp("[\\?&]" + varname + "=([^&#]*)");
			var str 	= (string == undefined)? window.location.href : string;
			var results = reg.exec(str);
			if(results == null) return "";
			else 				return results[1];
		},
		
		//send page by mail
		send: function(){
			var s  = "mailto:?subject=" + document.title;
			s 	  += "&body=I thought you might be interested in this page, \"" + document.title + "\". ";
			s	  += "You can view it at: " + location.href;
			document.location.href = s;
		},
		
	   /**
		* p RegExp test function. regex can be a RegExp object or String object. In the latter it's necessary to
		* replace '/' [ie. a simple String(RegExp obj]
		* @param	regex		RegExp object or String object
		* @param	value		string to be evaluated
		*/
		test: function(regex, value){
			if($.isArray(regex)){
				for(i in regex){  if($.p.test(regex[i], value)) return true; }
			} else {
				if(typeof regex == 'string')	regex = new RegExp(regex.replace(/^(\/)(.*)(\/)$/, '$2'));
				return regex.test(value);
			}
			return false;
		}
	}
})(jQuery);