var fileUploading = false 	//	true if file is currently uploading (ajax)
var maxImages = 10;			//	sets the maximum number of images to upload
var imageCount = 1;
var validator;

function saveTinyMce(){
	if (typeof(tinyMCE) != 'undefined'){
		tinyMCE.triggerSave();
	}
}

(function($){
	$(document).ready(function (){
		$('a#reloadCaptcha').livequery('click', function(){
			$("img#captcha").attr('src', '');
			$("img#captcha").attr('src', urlPath+'/captcha/'+Math.random());
			return false;
		});
		$('div#rate_1, div#rate_2, div#rate_3, div#rate_4, div#rate_5').hover(
			function(){
				to = $(this).attr('id').substring(5);
				if ($(this).hasClass('canrate') == false)
					return false;
				$(".rated").hide();
				for (i = 1; i <= to; i++){
					$("#rate_" + i).css('background-position', '0 -60px');
				}
			},
			function(){
				if ($(this).hasClass('canrate') == false)
					return false;
				$(".rated").show();
				for (i = 1; i <= 5; i++){
					$("#rate_" + i).css('background-position', '0 0');
				}
			}
		);
		$('div#rate_1, div#rate_2, div#rate_3, div#rate_4, div#rate_5').click(function(){
			if ($(this).hasClass('canrate') == false)
				return false;
			to = $(this).attr('id').substring(5);
			$("#rate").load(rateUrl + to);
		});
		
		$('a.injectImage').click(function() {
			injectImageUpload(this);
			return false;
		});
		
		$("form.pollVote").livequery('submit', function(){
			div = $(this).parents('div').get(0);
			$.post($(this).attr('action'), $(this).serialize(), function(data){
				$(div).html(data);
			});
			return false;
		});
		
		//	Random password generator for registration page
		$("#generateRandPassword").livequery('click', function(){
			$(".genpassword").val(randomString(12));
		});
		
		/*
		$("input[id^='image']").livequery('change', function(){
			if (!isImage(getExt($(this).val())))
				return false;
			ajaxFileUpload($(this).attr('id'));
			$(this).attr('disabled', true);
		});
		removeImage();
		*/
		/*
		list = $('img.clearbox');
		$.each(list, function() {
			$(this).wrap('<a class="clearbox" title="' + $(this).attr('title') + '"href="' + $(this).attr('src') + '"></a>');
		});

		$(".doimgswap").click(function(){
			$('#imgswap').attr('src', $(this).attr('src').replace('small', ''));
		});
		*/
		
		//	TinyMCE configuration
		var tinyMceConfig = [{
			mode : "textareas",
			plugins : "ibrowser,safari",
			theme : "advanced",
			editor_selector : "wysiwyg",
			theme_advanced_buttons3_add : "ibrowser",
			extended_valid_elements : "iframe[src|width|height|name|align]",
			theme_advanced_statusbar_location : "bottom",
			theme_advanced_resizing : true
		},{
			mode : "textareas",
			theme : "simple",
			extended_valid_elements: "embed[id|style|type|src|quality|bgcolor|scale|wmode|salign|FlashVars|width|height|allowfullscreen]",
			theme_advanced_buttons1 : "bold,italic,underline,link,unlink,bullist,blockquote,undo,code", 
			theme_advanced_buttons2 : "", 
			theme_advanced_buttons3 : "",
			editor_selector : "wysiwygsim",
			theme_advanced_resizing : true
		}];
		
		arr = $('.wysiwyg');
		if (arr.length > 0){
			tinyMCE.settings = tinyMceConfig[0];
			jQuery.each(arr, function() {
				tinyMCE.execCommand('mceAddControl', true, $(this).attr('id')); 
			});
		}

		arr = $('.wysiwygsim');
		if (arr.length > 0){
			tinyMCE.settings = tinyMceConfig[1];
			$.each(arr, function() {
				tinyMCE.execCommand('mceAddControl', true, $(this).attr('id')); 
			});
		}
		
		$('a.lightbox').lightBox({txtImage : ''});
		
		$("form.validate").livequery('submit', function(){
			var validator = $(this).validate();
			
			saveTinyMce();
			
			if (fileUploading == false){
				if ($(this).valid() == true) {
					this.submit();
				}
				else
					return false;
			}
			else {
				alert('Šiuo metu ikeliamas failas.');
			}
			return false;
		});
		
		/*
		//	Catalog categories menu slider (first level)
		$('div.first a').click(function(){			
			//	finding all other first level li divs and removing all styles
			//	$(this).parents('ul#catalogTree', 0).find('li div.first').css('background', 'url(/img/catalog-tree-element.png) no-repeat');
			$(this).parents('ul#catalogTree', 0).find('li ul').slideUp("slow", function(){
				$(this).css('border', '0');
				$(this).parent().find('div:first').css('background', 'url(/img/catalog-tree-element.png) no-repeat');
			});
		
			li = $(this).parents('li', 0);
			ul = li.find('ul:first');
			
			//	Calculating how many childs ul has
			childLis = ul.find('li');
			
			//	If ul is hidden
			if (ul.css('display') == 'none'){
				//	Loading categorie to main view
				$('#main').load($(this).attr('href'));
				
				li.find('div:first').css('background', 'url(/img/catalog-tree-element-selected.png) no-repeat');
				if (childLis.length > 0){
					ul.css('border-bottom', '2px solid #c76827').css('border-left', '2px solid #c76827').css('border-right', '2px solid #c76827');
					ul.slideDown("slow");
				}
			}
			//	otherwise it is shown 
			else {
				if (childLis.length > 0){
					ul.slideUp("slow", function(){
						ul.css('border', '0');
						li.find('div:first').css('background', 'url(/img/catalog-tree-element.png) no-repeat');
					});
				}
			}
			
			return false;
		});
		
		//	Catalog categories menu slider (second level)
		$('div.second a').click(function(){
			li = $(this).parent().parent();
			ul = li.find('ul:first');

			//	Calculating how many childs ul has
			childLis = ul.find('li');

			//	finding all other second level li divs and removing all styles
			$(ul).slideUp("slow", function(){
				$(this).css('border', '0');
			//	$(this).parent().find('div:first').css('background', 'url(/img/catalog-tree-element.png) no-repeat');
			});

			//	If ul is hidden
			if (ul.css('display') == 'none'){
				//	Loading categorie to main view
				$('#main').load($(this).attr('href'));
			
			//	li.find('div:first').css('background', 'url(/img/catalog-tree-element-selected.png) no-repeat');
				if (childLis.length > 0){
					li.find('div:first a').css('text-decoration', 'underline');
				//	ul.css('border-bottom', '2px solid #c76827').css('border-left', '2px solid #c76827').css('border-right', '2px solid #c76827');
					ul.slideDown("slow");
				}
			}
			//	otherwise it is shown 
			else {
				if (childLis.length > 0){
					ul.slideUp("slow", function(){
						li.find('div:first a').css('text-decoration', 'none');
					//	ul.css('border', '0');
					//	li.find('div:first').css('background', 'url(/img/catalog-tree-element.png) no-repeat');
					});
				}
			}
			
			return false;
		});
				
		//	Catalog categories menu slider (third level)
		$('div.third a').click(function(){
			//	Loading categorie to main view
			$('#main').load($(this).attr('href'));
			
			return false;
		});
		*/
	});
})(jQuery);

function injectImageUpload(_this){
	if (imageCount == maxImages)
		return false;
	imageCount = imageCount + 1;
	model = '<div class="imgup"><div class="show"><img class="img" src="" alt=""/><img class="del" src="/css/blueprint/plugins/buttons/icons/cross.png" alt="Trint" title="Trinti" /></div><input type="hidden" value="" name="data[Image][img'+imageCount+']" class="name"/><div class="input"><input type="file" id="image'+imageCount+'" value="" accept="jpg|jpeg|png|gif" name="data[Image][image'+imageCount+']" class=""/></div><div class="uploading" style="">Ikeliama..</div><div class="clear"></div></div>';
	p = $(_this).parent();
	inner = p.find('div.imageUploader').append(model);
}

/* Helpers */
function randomString(string_length) {
	var chars = "0123456789abcdefghiklmnopqrstuvwxyz";
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}
function strpos(haystack, needle, offset){
    var i = (haystack+'').indexOf( needle, offset ); 
    return i===-1 ? false : i;
}
function empty( mixed_var ) {
    var key;
    if (mixed_var === "" ||
        mixed_var === 0 ||
        mixed_var === "0" ||
        mixed_var === null ||
        mixed_var === false ||
        mixed_var === undefined
    ){
        return true;
    }
    if (typeof mixed_var == 'object') {
        for (key in mixed_var) {
            return false;
        }
        return true;
    }
    return false;
}
function getExt(str){
	dot = str.lastIndexOf(".");
	if(dot == -1) return false; 
	return str.substr(dot + 1,str.length).toLowerCase(); 
}
function isImage(ext){
	if (ext == 'jpg' || ext == 'jpeg' || ext == 'png' || ext == 'png' || ext == 'gif')
		return true;
	else
		return false;
}

function intval( mixed_var, base ) {  
    var tmp;  
  
    var type = typeof( mixed_var );  
  
    if(type == 'boolean'){  
        if (mixed_var == true) {  
            return 1;  
        } else {  
            return 0;  
        }  
    } else if(type == 'string'){  
        tmp = parseInt(mixed_var * 1);  
        if(isNaN(tmp) || !isFinite(tmp)){  
            return 0;  
        } else{  
            return tmp.toString(base || 10);  
        }  
    } else if(type == 'number' && isFinite(mixed_var) ){  
        return Math.floor(mixed_var);  
    } else{  
        return 0;  
    }  
}  