/*
if (!console) {
	var console = {
			log: function(message) {
			};
	};
}
*/

var quote = function(somestr) {
	return somestr.replace(/['"]/g, '\\$&');
}

/*
 Resolvuje wlasne dodatki do selectorow:
 	^ - parent danego elementu
 Jesli nie wykryje dodatku, normalnie resolvuje selector.
*/
var resolve = function(scope, selector) {
	return devlib.resolve(scope, selector);
}

// UWAGA: do tego obiektu wkladamy wszystkie nowe funkcje (zeby byly w namespace devlib)
var devlib = {
	STATUS_OK: 0,
	STATUS_ERR: 1,
		
	/*
	 * przyklady uzycia:
	 *  resolve(this, '^') -> this.parent()
	 *  resolve(this, '^^') -> this.parent().parent()
	 *  resolve(this, 'this > li') -> this.find('li')
	 */
	resolve: function(scope, selector) {
		if (selector.substring && selector.substring(0, 1) == '^') {
			scope = scope.parent();
			if (selector.length > 1)
				return devlib.resolve(scope, selector.substring(1));
			else
				return scope
		} else if (selector == 'next' || selector == '->') {
			return scope.next();
		} else if (selector == 'prev') {
			return scope.prev();
		} else if (selector == 'this') {
			return scope;
		} else if (selector.substring && selector.substring(0, 7) == 'this > ') {
			return $(selector.substring(7), scope);
		} else {
			return $(selector);
		}
	},
	
	processCommands: function(me, _cmdstr, response) {
		// operations on elements
		var hide = function(elem) {
			devlib.resolve(me, elem).hide();
		}
		var show = function(elem) {
			devlib.resolve(me, elem).show();
		}
		var replaceWith = function(elem, data) {
			devlib.resolve(me, elem).replaceWith(data);
		}
		var html = function(elem, data) {
			devlib.resolve(me, elem).html(data);
		}
		var toggle = function(elem) {
			devlib.resolve(me, elem).toggle();
		}
		var append = function(elem, data) {
			devlib.resolve(me, elem).append(data);
		}
		var prepend = function(elem, data) {
			devlib.resolve(me, elem).prepend(data);
		}
		var focus = function(elem) {
			devlib.resolve(me, elem).focus();
		}
		// Focus first input
		var ffi = function(elem) {
			devlib.resolve(me, elem).find(':input:visible:enabled:first').focus();
		}
		
		// Display form errors returned by the server
		var showFormErrors = function(elem) {
			var myform = devlib.resolve(me, elem);
			myform.find('.errorlist').remove();
			var errors = response.json;
			for (var k in errors) {
				//console.log(k);
				//console.log(errors[k]);
				myform.find('label[for=id_' + k + ']').after(errors[k]);
			}
		}
		
		if (response && response.html)
			response.html = $(response.html);
		if (response && response.json) {
			response.json = eval(response.json);
			//console.log(response.json);
		}
		//console.log('evaluating: ' + _cmdstr);
		eval(_cmdstr);
		// We also evalute the response JS if any was provided
		if (response) {
			if (response.js) {
				//console.log('JS:' + response.js);
				eval(response.js);
			}
			if (response.html) {
				devlib.runLib(response.html);
			}
		}
	},
	
	notify: function(msg, text, time) {
		//alert('grittering');
		$.gritter.add({title: msg, text: text || ' ', time: time || 7000});
	},
	
	runLib: function(scope) {
		$('.hideonload', scope).hide();
	/*	
		$("a[click]", scope).click(function () {
			if ((typeof $(this).attr('click')) == 'object')
				return true;
			devlib.processCommands($(this), $(this).attr('click'));
			return false;
		});
	  */  
		// Display a confirmation question when we click on this element
		$('a[confirm], input[confirm][type=submit]', scope).click(function(event) {
			if (!confirm($(this).attr('confirm'))){
				event.stopImmediatePropagation();
				return false;
			}
		});
		
	    $('.growl', scope).each(function () {
	    	devlib.notify($(this).html());
	    });
	    
	    $("a.async2", scope).click(function () {
	        var success = $(this).attr('success');
	        var failure = $(this).attr('failure');
	        var callback = $(this).attr('callback');
	        var post_data = $(this).attr('post-data');
	        var url = $(this).attr('href');
	        
	        var aelem = $(this);
	        
	        var callback_function = function(data) {
	        	data = JSON.parse(data);
	        	//console.log('-----');
	        	//console.log(success);
	        	//console.log(failure);
	        	//console.log(data.status);
	        	devlib.processCommands(aelem, (data.status == devlib.STATUS_OK) ? success : failure, data);
	        }
	        
	        if (post_data)
	        	$.post(url, post_data, callback_function)
	        else
	        	$.get(url, callback_function);

	        return false;
	    });
	    
	    // Form submission
	    $("form.async2", scope).each(function () {
	    	var myform = $(this);
			var beforecb = eval($(this).attr('beforecb'));
			var successjs = $(this).attr('success');
			var failurejs = $(this).attr('failure');
			var handleckedit = $(this).attr('handle-ckedit');

			var opts = {
		        	   dataType: 'json',
					   beforeSubmit: beforecb || function(){return true;},
		        	   success: function (resp) {
		        			if (resp.status == 0) {
		        	        	devlib.processCommands(myform, successjs, resp);
		    					myform.find('.errorlist').remove();
		        			} else {
		        				// By default we show errors in the form
		        	        	devlib.processCommands(myform, failurejs || 'showFormErrors("this")', resp);
		        			}
		        	   }
		    };
			
			if (handleckedit)
				opts.beforeSubmit = function (data, form, options) {
					for (key in data) {
						console.log('old value: ' + data[key].value);
						if (data[key].name == handleckedit) 
							data[key].value = CKEDITOR.instances['id_' + handleckedit].getData();
						console.log('new value: ' + data[key].value);
					}
				}
			
	        $(this).ajaxForm(opts);
	    });   
	    
	    // Show some element while we hover over another
		$('div[hover-show],span[hover-show]', scope).hover(
		        function () {
		        	resolve($(this), $(this).attr('hover-show')).show();
		        },
		        function () {
		        	resolve($(this), $(this).attr('hover-show')).hide();
		        }
		);
	    $('div[hover-show],span[hover-show]', scope).each(function() {
	    	resolve($(this), $(this).attr('hover-show')).hide();
	    });

		// Focus the selected element
		$('.focusnow', scope).focus();

		// Externally editable by a click on some other element
	    $("span[editable-external]", scope).each(function() {
	        $(this).editable($(this).attr('editable-external'), { 
				        event  : 'dblclick',
				        type   : 'text',
				        data   : $(this).attr('editable-data'),
				        name   : 'value',
				        submitdata: {'oid': $(this).attr('editable-oid')},
				        submit : 'OK'
	        });
	    });
	    
	    $("span[editable],div[editable]", scope).each(function() {
	    	var submitdata = {
	    			'oid': $(this).attr('editable-oid'), 
	    			'varname': $(this).attr('editable-name') || 'value'
	    	};
	    	
	    	var options = { 
	    			indicator : "<img src='/static/devlib/jeditable/img/indicator.gif'>",    			
			        event  : $(this).attr('editable-event') || 'click',
			        type   : $(this).attr('editable-type') || 'text',
			        name   : $(this).attr('editable-name') || 'value',
			        rows   : 10,
			        cols   : 80,
			        tooltip: $(this).attr('editable-tooltip')||undefined,
			        submitdata: submitdata,
			        submit : 'Save',
			        cancel : 'Cancel',
			        select : true,
			        onblur : $(this).attr('editable-onblur') || 'cancel',
			        csseditclass: $(this).attr('csseditclass') || undefined,
			        ckeditor: { customConfig : '/static/js/ckeditor_config.js' },
                    callback: function(innerHTML, settings) { $(this).trigger('saved', [innerHTML, settings]); }
	    	};
	    	
	    	var loadurl = $(this).attr('editable-loadurl');
	    	if (loadurl) {
	    		options.loadurl = loadurl;
	    	}
	    	
	    	if ($(this).attr('editable-placeholder')) {
	    		options.placeholder = $(this).attr('editable-placeholder');
	    		//console.log(options.placeholder);
	    	}
	    	
	    	// Data can be raw json data or it can be the ID of the element containing the data
	    	if ($(this).attr('editable-data')) {
	    		options.data = $(this).attr('editable-data');
	    	} else if ($(this).attr('editable-datavar')) {
	    		options.data = eval($(this).attr('editable-datavar'));
	    	}
	    	
	        $(this).editable($(this).attr('editable'), options);
	    });	

        $("span[editable-widget=JTextArea]").css('white-space', 'pre-wrap');

	    $("a[edits-element]", scope).each(function () {
	        $(this).bind('click', function() {
	            $($(this).attr('edits-element')).dblclick();
	            return false;
	        });
	    });
	    
	    $("textarea.ckedit", scope).each(function () {
	    	CKEDITOR.replace(this, { customConfig : '/static/js/ckeditor_config.js' });
	    });

	    // Ajax clickable links, if has 'hide' attr it will hide the given element after performing the request
	    $("a.async", scope).click(function () {
	    	// If callback is set to 'server' then it will eval server response.
	        var hideel = $(this).attr('hide');
	        var showel = $(this).attr('show');
	        var replaceel = $(this).attr('replace');
	        var setel = $(this).attr('set');
	        var callback = $(this).attr('callback');
	        var post_data = $(this).attr('data-post');
	        var url = $(this).attr('href');
	        
	        /*
	    	if (jQuery.mask) {
	    		$(this).mask('Loading..');
	    	}
	    	*/
	        
	        var aelem = $(this);
	        
	        var callback_function = function(data){
	        	//console.log('in callback');
	    		if (hideel) {
	    			resolve(aelem, hideel).hide();
	    		}
	    		if (showel) {
	    			resolve(aelem, showel).show();
	    		}
	    		if (replaceel) {
	    			resolve(aelem, replaceel).replaceWith(data);
	    			runLib(data);
	    		}
	    		if (setel) {
	    			var el = resolve(aelem, setel);
	    			resolve(aelem, setel).html(data);
	    			runLib(el);
	    		}
	    		if (callback == 'server') {
	    			eval(data);
	    		} else if (callback) {
	    			eval(callback);
	    		}
	        }
	        
	        if (post_data){
	        	$.ajax({
	        		type: "POST",
	        		url: url,
	        		data: post_data,
	        		success: callback_function
	        	});
	        }
	        else{
	        	//here should be also asynchronic?
	        	$.get(url, callback_function);
	        }
	        return false;
	    });
	    	
	    $("input[autocomplete]", scope).each(function () {
	    	// Creates an AJAX autocompleted field, if you provide 'jumpto' then data returned
	    	// as the entries needs to provide a 'text' field and a 'url' field.  And after
	    	// picking an entry the user will be redirected to the entries url.
	    	var jumpto = $(this).attr('jumpto');
	    	var opts = {};
	    	
	    	if (jumpto) {
	    		opts.formatItem = function(item) {
	    			return item.text;
	    		}
	    	}
	    	
	    	var ac = $(this).autocomplete($(this).attr('autocomplete'), opts);
	    	
	    	if (jumpto) {
	    		ac.result(function (event, item) {
	    			location.href = item.url;
	    		});
	    	}
	    });

	    // Ajax loader links - will load given HTML from given URL to given element 
	    $("a[load-from]", scope).click(function () {
	        var source = $(this).attr('load-from');
	        var destination = $(this).attr('load-to');
	        $(destination).load(source);
	        return false;
	    });
	    
	    $("div[load-from]", scope).each(function(){
	    	var source = $(this).attr('load-from');
	    	if ($(this).attr('js-url') == undefined){
	    		$(this).load(source);
	    	}else{
	        	$(this).load(source, callback=function(){
	        		$.getScript($(this).attr('js-url'), function(){})
	        	});
	    	}
	    	return false;
	    });
	    
	    // Form submission
	    $("form.async", scope).each(function () {
	        $(this).ajaxForm({
	        	   dataType: 'script'
	        });
	    });
	    
	    // Form submission
	    $("form.asyncvalidated", scope).each(function () {
	    	var myform = $(this);
	        $(this).ajaxForm({
	        	   dataType: 'json',
	        	   success: function (resp) {
	        			if (resp.status == 0) {
	        				myform.hide();
	        				myform.clearForm();
	        				resolve(myform, myform.attr('result-append')).append(resp.html);
	        			} else {
	        				//console.log(resp.errors);
	    					myform.find('.errorlist').remove();
	        				for (var k in resp.errors) {
	        					//console.log(k);
	        					//console.log(resp.errors[k]);
	        					myform.find('label[for=id_' + k + ']').after(resp.errors[k]);
	        					//myform.
	        				}
	        			}
	        	   }
	        });
	    });    

	    if (jQuery.datepicker) {
	    	$(".date-picker", scope).datepicker({
	    		changeMonth: true,
	    		changeYear: true,
	    		yearRange: '-70:+70',
	    		dateFormat: 'yy-mm-dd'
	    	});
	    }
	    
	    $("select[fbcomplete]", scope).each(function () {
	    	$(this).fcbkcomplete({
		        json_url: $(this).attr('fbcomplete'),
		        cache: false,
		        filter_case: false,
		        filter_hide: true,
				firstselected: true,
		        //onremove: "testme",
				//onselect: "testme",
		        filter_selected: true,
		        newel: false        
	    	});
	    });
	    
	    
	    $('a[form-dialog]', scope).click(function () {
	    	$.ui.dialog.defaults.bgiframe = true;
	    	/*
	    	 * przypadki uzycia:
	    	 * - klikam i edytuje jakies dane sobie
	    	 * 
	    	 * - ladujemy forma z serwera
	    	 * - umieszczamy go w przygotowanym elemencie jesli jeszcze go tam nie ma
	    	 * - z przygotowanego elementu robimy dialog w momencie zaladowania
	    	 * - w linku sobie trzymamy losowe ID elementu
	    	 * - 
	    	 */
	    });
	    
	    //dialog do wyswietlania informacji
	    $('div.dialog-msg', scope).each(function(){
	    	$(this).dialog({ 
	    		modal: true,
	    		height: 50,
	    		minHeight: 70
	    	});
	    });
	    
		$("a[click-hide]", scope).click(function () {
			$($(this).attr('click-hide')).hide();
			return false;
		});
		
	    $('a[click-toggle]', scope).each(function() {
	    	//alert('hiding ' + $(this).attr('click-toggle'));
	        resolve($(this), $(this).attr('click-toggle')).hide();
	    });
		
		$('a[click-toggle]', scope).click(function() {
			resolve($(this), $(this).attr('click-toggle')).toggle();
			return false;
		});
		

	    $('a[click-slide]', scope).each(function() {
	        $($(this).attr('click-slide')).hide();
	    });
		$('a[click-slide]', scope).click(function() {
			$($(this).attr('click-slide')).slideToggle();
			return false;
		});
		
		$('a[click-focus]', scope).click(function() {
			resolve($(this), $(this).attr('click-focus')).focus();
		});

		
	    $('input[focus-show],textarea[focus-show]', scope).each(function() {
	        $($(this).attr('focus-show')).hide();
	    });
		$('input[focus-show],textarea[focus-show]', scope).focus(function() {
			$($(this).attr('focus-show')).show();
		});
		
		$('input.select', scope).click(function() {
			$(this).focus();
			$(this).select();
		});

		$("a[click-replace-with]", scope).click(function () {
			$(this).replaceWith($(this).attr('click-replace-with'));
			return false;
		});
		
		$("a[click-remove]", scope).live('click', function () {
			resolve($(this), $(this).attr('click-remove')).remove();
			return false;
		});
	    
		if ($('.any').autoResize) {
			$('.auto-resize', scope).autoResize({
				 limit: 250, 
				 extraSpace: 30
			});
		}
		
		$("select[save-choice]", scope).change(function () {
			$("select option:selected", this).each(function () { 
	            alert($(this).text());
	        }); 
		});
		
		$("form.valid-form", scope).each(function(){
			$(this).validate();
		});
		
		// from jquery.form.default-value in devlib/media
		if (typeof installDefaultValue == 'function') {
			installDefaultValue(scope);
		}

		$('input[submit-not-null]').keyup(function(){
			if ($(this).val()==$(this).attr('null-value')||$(this).val()==''){
				$($(this).attr('submit-not-null')).hide();
			}
			else{
				$($(this).attr('submit-not-null')).show();
			}
		});
		
		$('input[type=checkbox][post-url]').click(function() {
		  	$.post($(this).attr('post-url'),{data: $(this).attr('checked')}, function(news) {
		    	if(news == 'OK') {
		    		$(this).css('background-color', '#b6fd90');
		    	};
		    });
		 });
		
		if (typeof DISABLE_ALL_BUTTONS_ON_SUBMIT != 'undefined') {
			$('form').submit(function() {
			    // On submit disable its submit button
			    $('input[type=submit]', this).attr('disabled', 'disabled').val('Wait..');
			});
		}
		
		$("div.overlay").each(function(){
			opts= {'api':true};
						
			if ($(this).attr('left')){
				opts.left = eval($(this).attr('left'));
			}
			
			if ($(this).attr('lib')){
				eval($(this).attr('lib'))($(this));
			}
			$(this).overlay(opts).load();
		})
		
		$("input[null-value], textarea[null-value]", scope).each(function (){
			if ($(this).val()!=$(this).attr('null-value')) {
				$(this).val($(this).attr('null-value'));
			};
			
			$(this).focus(function(){
				if ($(this).val() == $(this).attr("null-value")){
					$(this).val('');
				};
			});
			$(this).blur(function(){
				if ($(this).val()==''){
					$(this).val($(this).attr('null-value'));
				};
			});
		});

		if ($.fn.ThreeDots) {
	        $(".ellipsis").parent().ThreeDots({
	            max_rows: 1,
	            alt_text_t: true,
	            alt_text_e: true,
	            text_span_class: 'ellipsis'
	        });
		}

		for (hookidx in devlib.runLibHooks) {
			devlib.runLibHooks[hookidx](scope);
		}
	    
	},
	
	runLibHooks: [],

	addLibHook: function(func) {
		// installs a hook to be ran alwyas when runLib is ran
		devlib.runLibHooks.push(func);
	},
	
	myLoad: function (selector, url, dataSelector, method) {
		// A version of the jquery $(..).load but installing all library callbacks on the returned data.
		if (jQuery.mask) {
			$(selector).mask('Loading..');
		}

		$.get(url, function(data) {
			if (jQuery.unmask) {
				$(selector).unmask();
			}
			
			var el = $(data);
			
			if (dataSelector) {
				el = $(dataSelector, el).html();
			}

			if (method == 'append') {
				$(selector).append(el);
			} else if (method || method == 'set') {
				$(selector).html(el);
			} else if (!method || method == 'replace') {
				$(selector).replaceWith(el);
			}
			//console.log('running lib on ' + selector);
			devlib.runLib($(selector));
		});
	},	
	
	
	addSelectOption: function (selector, name, value) {
			$(selector).append('<option value="' + value + '" selected="1">' + name + '</option>');
	},
	
	makeJSTree: function(selector, scope, options, direct_options) {
		if (!scope) {
			scope = document.body;
		}
		var params = {
			data: {
				async: true,
				type: 'json',
				opts: {
					url: options.subElementUrl
				}
			},
			callback: {
				onchange: options.onClick,
				onmove: function(NODE, REF_NODE, TYPE, TREE_OBJ, RB) {
				    if(TYPE != "inside") { 
		    	  		TYPE = "inside"; 
				    	REF_NODE = $(NODE).parents("li:eq(0)").get(0); 
				    }	    
			        parent_id = $(REF_NODE).attr('id');
			        if (!parent_id) {
				        parent_id = 0;
			        }
			        if (options.onChangeParent) {
			        	options.onChangeParent(NODE.id, parent_id);
			        }
				}
			}
		}
		
		if (options.callback_check_move){
			params.callback.check_move = options.callback_check_move;
		}
		
		if (options.selected) {
			params.selected = options.selected;
		}
		if (options.opened) {
			params.opened = options.opened;
		}
		if (options.initialData) {
			// Make sure static is not used once the tree has loaded for the first time
			/*params.callback.onload = function (t) { 
				t.settings.data.opts.static = false; 
			},*/
			// Take care of refresh calls - n will be false only when the whole tree is refreshed or loaded of the first time
			params.callback.beforedata = function (n, t) { 
				if (n == false) t.settings.data.opts.static_data = options.initialData; 
				else {
					t.settings.data.opts.static_data = false;
					return { id: $(n).attr('id') || 0 }
				}
			}
		}
		options = $.extend(options, direct_options);
		$(selector, scope).tree(params);
	}
}

// Kompatybilnosc wstecz
var addLibHook = devlib.addLibHook;
var runLib = devlib.runLib;
var myLoad = devlib.myLoad;

$(document).ready(function() {	
	devlib.runLib(document.body);
});


/*
 * Dostarcz:
 * - subElementUrl - URL from which the list of subelements will be taken, it will receive the 'id'
 * 			parameter, and the data returned should be in the format: http://www.jstree.com/documentation#datastores
 * - onClick: i.e.
 * 			function(NODE, TREE_OBJ) {
			  	$('#wiki-body-parent').load($(NODE).children("a:eq(0)").attr("url") + ' #wiki-body');
			},
			
	- onChangeParent i.e.:
			function(node_id, parent_id) {
		        var actionUrl = "/wiki/move_page/" + node_id + "/" + parent_id + '/';
			    $.get(actionUrl);				
			}
 */
function makeTree(selector, scope, subElementUrl, onClick, onChangeParent, initialData) {
	// stara wersja NIE UZYWAC - zamiast tego uzyj makeJSTree
	return devlib.makeJSTree(selector, scope, { 
						subElementUrl: subElementUrl, 
						onClick: onClick, 
						onChangeParent: onChangeParent, 
						initialData: initialData
	});
}

var makeJSTree = devlib.makeJSTree;


var runGalleriffic = function (opt) {
	// We only want these styles applied when javascript is enabled
	//$('div.navigation').css({'width' : '200px', 'float' : 'left'});
	//$('div.content').css('display', 'block');
	if (!opt)
		opt = {};

    // Initially set opacity on thumbs and add
    // additional styling for hover effect on thumbs
    var onMouseOutOpacity = 0.67;
    $('#thumbs ul.thumbs li').css('opacity', onMouseOutOpacity)
        .hover(
            function () {
                $(this).not('.selected').fadeTo('fast', 1.0);
            }, 
            function () {
                $(this).not('.selected').fadeTo('fast', onMouseOutOpacity);
            }
        );

    var player;

	// Initialize Advanced Galleriffic Gallery
	var gallery = $('#thumbs').galleriffic({
		delay:                     2500,
		numThumbs:                 10,
		preloadAhead:              2,
		enableTopPager:            true,
		enableBottomPager:         true,
		enableKeyboardNavigation:  false,
		maxPagesToShow:            4,
		imageContainerSel:         '#slideshow',
		controlsContainerSel:      '#controls',
		captionContainerSel:       '#caption',
		loadingContainerSel:       '#loading',
		renderSSControls:          true,
		renderNavControls:         true,
		playLinkText:              opt.playLinkText || 'Slideshow',
		pauseLinkText:             opt.pauseLinkText || 'Pause',
		prevLinkText:              opt.prevLinkText || '&laquo; Previous photo',
		nextLinkText:              opt.nextLinkText || 'Next photo &raquo;',
		nextPageLinkText:          opt.nextPageLinkText || 'Next &raquo;',
		prevPageLinkText:          opt.prevPageLinkText || '&laquo; Previous',
		enableHistory:             false,
		autoStart:                 false,

		onPageTransitionIn: function() {
			var pageno = this.displayedPage;
			var pagelen = this.numThumbs;

			var first = pageno * pagelen;
			var last = first + pagelen;

			var ul = this.find('ul.thumbs');
			var imgs = ul.find('img');

			for (var i=first;i<last;++i) {
				var img = imgs.eq(i);
				if (!img.attr('lazysrc'))
					continue;
				img.attr('src', img.attr('lazysrc'));
				img.attr('lazysrc', '');
			}

            $('#thumbs').show();
		},

        onTransitionIn: function(newSlide, newCaption, isSync) {
            newSlide.css('opacity', 1);
            newCaption.css('opacity', 1);

            vidrel = $('.video[rel]', newCaption);
            if (vidrel.length) {
                if (!player) {
                    player = flowplayer("flowplayer", "/static/devlib/flowplayer/flowplayer-3.1.5.swf", {
                        clip: { autoPlay: false, autoBuffering: true }
                    });
                }
                newSlide.hide();
                player.show();
                player.play(vidrel.attr('rel'));
            } else if (player) {
                player.pause();
                player.hide();
                $('#flowplayer').height('1px');
                newSlide.show();
            }
        },

        onTransitionOut: function(previousSlide, previousCaption, isSync, transitionOutCallback) {
            transitionOutCallback();
        }
	});
	/**** Functions to support integration of galleriffic with the jquery.history plugin ****/

	// PageLoad function
	// This function is called when:
	// 1. after calling $.historyInit();
	// 2. after calling $.historyLoad();
	// 3. after pushing "Go Back" button of a browser
/*
	function pageload(hash) {
		// alert("pageload: " + hash);
		// hash doesn't contain the first # character.
		if(hash) {
			$.galleriffic.gotoImage(hash);
		} else {
			gallery.gotoIndex(0);
		}
	}

*/
	// Initialize history plugin.
	// The callback is called at once by present location.hash. 
	//$.historyInit(pageload, "advanced.html");

	// set onlick event for buttons using the jQuery 1.3 live method
    /*
	$("a[rel='history']").live('click', function(e) {
		if (e.button != 0) return true;
			
		var hash = this.href;
		hash = hash.replace(/^.*#/, '');

		// moves to a new page. 
		// pageload is called at once. 
		// hash don't contain "#", "?"
		$.historyLoad(hash);

		return false;
	});
    */

		/****************************************************************************************/	
	//$('a[del-hash]').live('click', function(e) {
	//	if (!gallery.removeImageByHash($(this).attr('del-hash')))
	//		alert('Fotka została skasowana');
	//
	//		e.preventDefault();
	//});
}

var runUploaderLib = function(scope){
	//	Put html into yor code
    //<input id="uploader" name="fileInput" type="file" file-limit="3" size-limit="1572864000" session-key="{{session_key}}"/>
	//<a href="javascript:$('#uploader').uploadifyUpload();">Wgraj plik</a>
		
    var up = $('#uploader', scope);
    if (!up.length)
        up = $('.uploader', scope);
	var session_key = up.attr('session-key');
	var scriptData = eval( "(" + up.attr('post_data')+")");
	var file_limit = parseInt(up.attr('file-limit') || '30');
	var size_limit = parseInt(up.attr('size-limit') || '10000000'); 
	var width_button = parseInt(up.attr('width-button')) || 110; 
	var height_button = parseInt(up.attr('height-button')) || 30;
	var redirect_url = up.attr('redirect-url');
	var redirect_error_url = up.attr('redirect-error-url')||redirect_url;
    var success = up.attr('success') || false;
	var button_url = up.attr('button-url') || false;
	var auto_upload = eval(up.attr('auto-upload')) || false;
	var script = up.attr('script') || '/file/jquery_upload/';
	var multi = up.attr('multi') ? eval(up.attr('multi')) : true;
	var post_params = eval(up.attr('post_params')) || {}
	var queue_id = up.attr('queue-id') || false;
	
	var files_ids = new Array();
	
	up.uploadify({
        'uploader': '/static/devlib/uploadify/uploadify.swf',
        'expressInstall': '/static/devlib/uploadify/expressInstall.swf',
        'scriptData': scriptData || {'session_key': session_key},
        'script': script,
        'cancelImg': '/static/devlib/uploadify/cancel.png',
		'buttonImg': button_url,
        'fileDataName': 'file',
        'queueSizeLimit' : file_limit,
		'queueID': queue_id,
        'multi': multi,
        'buttonText': 'Wybierz',
		'width': width_button,
		'height': height_button,
        'sizeLimit': size_limit,
        'onQueueFull':onQueueFull,
        'onComplete':onComplete,
		'auto': auto_upload,
        'onAllComplete':onAllComplete,
        'onInit':onInit
	});
	
	function onQueueFull(event, size){
		return false;
	};
	
	function onComplete(event, queueID, fileObj, response, data){
		json_data = JSON.parse(response);
		if(parseInt(json_data.status) == devlib.STATUS_OK){
			files_ids[data.fileCount] = json_data.id;
		}
        return true;
	};
	
	function onAllComplete(event, data){
		GET = '?'
		
		for (i=0;i<files_ids.length;i++){
			GET = GET + "file_id=" + files_ids[i] + '&'
		}

        if (success) {
            eval(success)
		}
		else if (files_ids.length > 0 && redirect_url){
			top.location.href = redirect_url+GET;
		}
		else if (redirect_error_url){
			top.location.href=redirect_error_url;
		};
        
        return true;
	};	
	
	function onInit(event, data){};
};

function DumpObject(obj)
{
  var od = new Object;
  var result = "";
  var len = 0;

  for (var property in obj)
  {
    var value = obj[property];
    if (typeof value == 'string')
      value = "'" + value + "'";
    else if (typeof value == 'object')
    {
      if (value instanceof Array)
      {
        value = "[ " + value + " ]";
      }
      else
      {
        //var ood = DumpObject(value);
        //value = "{ " + ood.dump + " }";
      }
    }
    result += "'" + property + "' : " + value + ", ";
    len++;
  }
  od.dump = result.replace(/, $/, "");
  od.len = len;

  return od;
}

