function pageControlClass() {
    this.init();
}

pageControlClass.prototype = {
		
	// jquery ui datepicket format
	dateFormat: 'dd/mm/yy',
    
    /**
     * onload behaviour
     */
	init: function() {
        var localObject = this;
        
        // main menu
        $(function() {
        	// this is invoked only for main layout
        	if ($('#page_container').length==0)
        		return;
        	
            $('ol#menu li').not('.selected')
                .mouseenter(function() {
                    $(this)
                        .animate({
                                'top': -7
                            }, 'fast');
                })
                .mouseleave(function() {
                    $(this)
                        .animate({
                                'top': 0
                            }, 'fast');
                });
   
            // login, signup
            $('#form-signup').submit(function(e) {
            	e.preventDefault();
            	localObject.form.post($(this));
            });
            
            $('.signup')
                .click(function(e) {
                    $('div#signupdialog')
                        .dialog({
                            'closeText': 'close',
                            'modal': true,
                            'resizable': false,
                            'width': 500,
                            'buttons': {
                                'Sign up': function() {
                                	localObject.form.post($(this).children("form"));
                                },
                                'Cancel': function() {
                                	$(this).dialog('close');
                                }
                            },
                            'open': function() {
                                $('input', this).first().focus();
                            }
                        });
                    e.preventDefault();
                }); 
                
            // logowanie    
            $('#form-login').submit(function(e) {
            	e.preventDefault();
            	localObject.form.post($(this));
            });
            
            $('.login')
                .click(function(e) {
                    $('div#logindialog')
                        .dialog({
                            'closeText': 'close',
                            'modal': true,
                            'resizable': false,
                            'width': 500,
                            'buttons': {
                                'Login': function() {
                                    /*var dialog = this;
                                    $.post('/user/login', $('div.#logindialog form').serialize(), function(response) {
                                        if (response.success == true)
                                        {
                                            //$(dialog).dialog('close'); 
                                            location.reload();
                                        }
                                        else {
                                            $('<h2 class="error" />')
                                                .html(response.reason)
                                                .appendTo(dialog)
                                                .hide()
                                                .fadeIn(function() { $(this).fadeOut(function() { $(this).remove() } )} )
                                        }
                                    });*/
                                    localObject.form.post($(this).children("form"));
                                    
                                    
                                },
                                'Cancel': function() {
                                    $(this).dialog('close'); 
                                }
                            },
                            'open': function() {
                                $('input:first', this)
                                    .focus();
                            }
                        });
                    e.preventDefault();
                });
                $('div#logindialog')
                    .find('input', this)
                        .keyup(function(e) {
                            if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {  
                                $(this).parents('.ui-dialog').find('button:first').click();
                            }
                        });
                
            // messages div show/hide
            if ($('#global-messages').length>0)
            	$('#global-messages').slideDown();
            $('#global-messages').click(function(ev) {
            	$(this).slideUp();
            });
            
            $('.help')
            	.mouseout(function(e) {
            		$('div.dialog').dialog('close');
            	})
            	.not('.help2')
            		.mouseover(function(e){
		            	e.preventDefault();
		            	localObject.showHint(this);
		            });
            
            $('.help.help2').mouseover(function(e){
            	e.preventDefault();
            	localObject.showBigHint(this);
            });
                        
            /*shadowheight = $('div#header_content').height();
            $('div#header_content')
                .append($('<div class="shadow_top" />'))
                .append($('<div class="shadow_left" />').height(shadowheight))
                .append($('<div class="shadow_right" />').height(shadowheight))
                .append($('<div class="shadow_bottom_container"><div class="shadow_bottom" /></div>'));
            
            // cienie
            var shadowheight = $('div#page').height() - 20;
            $('div#page')
                .append($('<div class="shadow_top" />'))
                .append($('<div class="shadow_left" />').height(shadowheight))
                .append($('<div class="shadow_right" />').height(shadowheight))
                .append($('<div class="shadow_bottom_container"><div class="shadow_bottom" /></div>'));*/

        });
    },
    
    showHint: function(item)
    {
    	$('<div class="dialog" title="' + $(item).attr('title') + '">' + $(item).attr('alt') + '</div>').dialog({
    		//buttons: { "Ok": function() { $(this).dialog("close"); } }
    	});
    },
    
    showBigHint: function(item)
    {
    	var dialogitem = $(item).parent().parent().find('.dialog');
    	dialogitem.clone().dialog({
    		'width': dialogitem.attr('width') + 'px'
    	});
    },
    
    /** Ajax utils */
    ajax: {
    	
    	/** Wraps jquery ajax with ajax icon, error handling etc. **/
    	request: function(type, url, data, success) {
    		// TODO Start loading icon / increment counter
    		$.ajax({
    			url: url,
    			type: type,
    			data: data,
    			success: success,
    			
    			complete: function() {
    				// TODO End start loading icon here / decrement counter
    			},
    			
    			error: function(xhr, status) {
    				if (xhr.status == 401) {
    					window.location = "/error/notallowed";
    					return;
    				}
    				// development version of error handling - we have output from errorController as response
    				$('body').replaceWith(xhr.responseText);
    			}
    			
    		});
    	},
    	
    	get: function(url, data, success) {
    		this.request("GET", url, data, success);
    	},
    	
    	post: function(url, data, success) {
    		this.request("POST", url, data, success);
    	},
    	
    	isScript: function(xhr) {
    		return xhr.getAllResponseHeaders().match(/content-type: text\/javascript/i);
    	},

    	load: function(element, type, url, data, success, noreplace) {
    		var $this = this;
    		this.request(type, url, data, function(data, status, xhr) {
    			if (!$this.isScript(xhr)) {
    				var ne;
    				if (noreplace) {
    					$(element).empty();
    					ne = $(element).prepend(data);
    				} else {
    					ne = $(data);
    					$(element).replaceWith(ne);
    				}
    				if (ne)
    					document.loadComponents(ne);
    			}
    			if (success)
    				success(data, status, xhr);
    		});
    	},
    	
    	loadGet: function(element, url, data, success, noreplace) {
    		this.load(element, "GET", url, data, success, noreplace);
    	},

    	loadPost: function(element, url, data, success, noreplace) {
    		this.load(element, "POST", url, data, success, noreplace);
    	},

    	redirect: function(url) {
    		window.location = url;
    	}
    	
    },
    
    /** Form utils */
    form: {
    	
    	/** post ajax form and refresh it **/
    	post: function(form, success, noreplace) {
    		form = $(form);
    		var el = form;
    		if (form.attr('data-posttarget')) // can override target element
    			el = $(form.attr('data-posttarget'));
    		// don't wanna bother with closure scope and 'this', so I use pageControl
    		pageControl.ajax.loadPost(el, form.attr("action"), form.serialize(), success, noreplace); 
    	},
    	
    	/** applies errors on form inputs from Zend_Form; namespace - for elements namespace[element] **/
    	errors: function(form, errors, namespace) {
    		$.each(errors, function(i, a) {
    			name = i;
    			if (namespace)
    				name = namespace+'['+i+']';
    			$(form).find('[name="'+name+'"]:first').each(function(j, e) {
    				e = $(e);
    				$(e).addClass("form-error");
    				$.each(a, function(k, err) {
    					// insert message as next siblings to <div class="field"> container
    					$('<div class="form-error-msg">'+err+'</div>').insertAfter(e.closest("div.field"));
    				})
    			});
    		});
    	},
    	
    	/** submits form, el=form or and form control **/
    	submit: function(el) {
    		el = $(el);
    		if (el.get(0).tagName.toLowerCase()!="form")
    			el = el.closest("form");
    		if (el.length>0)
    			el.submit();
    		return false;
    	},
    	
    	/**
    	 * Adds hidden input to the form.
    	 */
    	addParam: function(form, name, value) {
    		form = $(form);
    		var input = form.find('input[name="'+name+'"]');
    		if (input.length>0) 
    			input.attr('value', value);
    		else
    			form.append('<input type="hidden" name="'+name+'" value="'+value+'"/>');
    	}
    	
    },
    
    /**
     * Autocomplete helpers
     */
    autocomplete: {
    	
    	/**
    	 * Autocomplete base function.
    	 * @param nameel Name input (text)
    	 * @param idel Id input (hidden). If not given is pointed by data-id="#ID" attribute of nameel
    	 * @param url Autocomplete URL
    	 */
    	base: function(nameel, idel, url) {
    		if (!idel)
    			idel = $($(nameel).attr('data-id'));

    		if (!url)
    			url = $(nameel).attr('data-url');
    		
    		$(nameel).autocomplete({
    			source: url,
    			select: function(event, ui) { 
    				$(nameel).val(ui.item.label);
    				$(idel).val(ui.item.value);
    				return false;
    			}
    		});
    	},
    	
    	programs: function(nameel, idel) {
    		pageControl.autocomplete.base(nameel, idel, "/autocomplete/program");
    	}
    	
    },
    
    /** various component management **/
    component: {
    	
    	toggle: function(el, on, effect) {
    		if (on) {
    			if (effect)
    				el.fadeIn();
    			else
    				el.show();
    		} else {
    			if (effect)
    				el.fadeOut();
    			else
    				el.hide();
    		}
    	},
    	
    	dialog: function(el, config) {
    		var config = $.extend({
                'closeText': 'close',
                'modal': true,
                'resizable': false,
                'width': 500
            }, config ?  config : {});
			el.dialog(config);
    	}
    	
    },
    
    util: {
    	
    	injectParam: function(url, params) {
    		for (param in params) {
	    		if (url.indexOf("?")==-1)
	    			url += "?";
	    		else
	    			url += "&";
	    		url += param+"="+params[param];
    		}
    		return url;
    	},
    	
    	url: function(el) {
    		return $(el).attr('href') || $(el).attr('data-url');
    	}
    	
    }
    
};

var pageControl = new pageControlClass();

/** dynamic components **/
document.pageComponents = {
	
	/** Switches with other element visibility depending on source checkbox state **/
	'chk-toggle': function(el) {
		el = $(el);
		var t = $(el.attr('data-target'));
		
		el.click(function() {
			pageControl.component.toggle(t, el.attr('checked'), true);
		});
		pageControl.component.toggle(t, el.attr('checked'), false);
	},
	
	/**
	 * Expects a script and executes it
	 */
	'ajax-js': function(el) {
		$(el).click(function(ev) {
			pageControl.ajax.get($(el).attr('href'));
			ev.preventDefault();
			return false;
		});
	},
	
	/** Displays dialog **/
	'dialog': function(el) {
		el = $(el);
		el.click(function(ev) {
			ev.preventDefault();

			var dialog = $('<div class="dialog"></div>').appendTo('body');
			pageControl.component.dialog(dialog, {title: el.attr('data-title')});
			var url = pageControl.util.url(el);
			if (url)
				pageControl.ajax.loadGet(dialog, url, null, null, true);
		});
	},
	
	/** Submits ajax form **/
	'ajax-submit': function(el) {
		el = $(el);
		el.click(function(ev) {
			pageControl.form.post(el.closest('form'));
			ev.preventDefault();
		});
	},
	
	/** Programs autocomplete */
	'autocomplete-programs': function(el) {
		pageControl.autocomplete.programs(el);
	},

	/** Programs autocomplete */
	'autocomplete': function(el) {
		pageControl.autocomplete.base(el);
	},
	
	/** Date picker **/
	'date': function(el) {
        $(el).datepicker({
            'changeYear': true,
            'changeMonth': true,
            'dateFormat': pageControl.dateFormat
        });
	},

	/** Date picker **/
	'mysql-date': function(el) {
		$(el).datepicker({
			'changeYear': true,
			'changeMonth': true,
			'dateFormat': 'yy-mm-dd'
		});
	}
}

document.loadComponents = function(root) {
	if (!root)
		root = document;
	$("[data-component]", root).each(function(i, e) {
		document.pageComponents[e.getAttribute("data-component")]($(e));
	});
};

$(document).ready(function() {
	document.loadComponents();
	/*$('.lazyload_ad').lazyLoadAd({
		forceLoad: false,
		debug        : false,
		xray         : false
	});*/
	var oldwrite = document.write;
	var time = 0;
	$('.lazyload_ad').each(function(index, item) {
		var code = $(item).find('code').html();
		
		var buffer = '';
		document.write = function(str) {
			buffer += str;
		};
		eval(code);
		//alert(buffer);
		
		/*jQuery.get(buffer, function(data) {
			var buffer2 = '';
			document.write = function(str) {
				buffer2 += str;
			};
			console.debug(data);
			eval(data);
			console.debug(buffer2);
			
			document.write = oldwrite;
		});*/

		setTimeout(function() {
			//console.debug(buffer);
			$(item).html(buffer);
		}, time);
		
		time = time + 1000;
		
	});
	document.write = oldwrite;
});








