$(document).ready(function(){
	try{
		$(".select_change_location").change(function(){
			val=$("option:selected",this).val();
			href=$(this).attr("title");
			location.href=href+val;
			//alert("val:"+val);
		});
	
		
		$(".selectLocationChange").change(function(){
			//alert($(this).val());
			location.href=$(this).val();
		});
		$(".buttonLocation").click(function(){
			location.href=$(this).attr("alt");
		});
	
		
	
		
		
		
		/*	$('.addCartLink').click({
			$('div#addCart').remove();
			$('body').append('<div id="addCart"></div>');
			$.post(URL_CART_FORM,{},function(response){
				tb_show("","#TB_inline?height=160&width=300&inlineId=addCart",1);
				$('div#addCart').html(response);
			});
		}); */ 
	
	
		$(document).ajaxComplete(function(event,request, settings){
			loadCmsScript();
		});
	
		loadCmsScript();
	
		$(".cart_info").each(function(){ 
			$(this).load("/cms/ajax.php?cmd=mod_cart-ajax-info");
			$(this).css("cursor","pointer");
			$(this).click(function(){ location.href = URL_CART_LINK; });
		});		
	
		$(".cartinfo").each(function(){ 
			$(this).load("/cartinfo");
			if(!$(this).hasClass("noLink")){
				$(this).css("cursor","pointer");
				$(this).click(function(){ location.href = URL_CART_LINK; });
			}
		});		
	}
	catch(e){
		alert(e);
	}

	
});	

//jsUrl("dfasdf&amp;dfafa"+"&amp;fsdafas");
function jsUrl(url){
	//alert(url);
	newurl=String(url).replace("&amp;","&");
	//newurl=String(newurl).replace("&amp;","&");
	//alert(newurl);
	return newurl;
}


function addCmsFavorite(type,id,idCallback,changeText){
	url="/cms/ajax.php?module=core&controller=favorites&action=ajaxfavorite&type="+type+"&id="+id;
	if(changeText=="true"){
		url+="&changeText=true";
		$("#"+idCallback).load(url);
	}
	else{
		$("#"+idCallback+" span").load(url);
	}
	
}

function serverTime() { 
    var time = null; 
    $.ajax({url: '/cms/serverTime.php', 
        async: false, dataType: 'text', 
        success: function(text) { 
            time = new Date(text); 
        }, error: function(http, message, exc) { 
            time = new Date(); 
    }}); 
    return time; 
}
function addToCompare(id,idCallback,changeText){
	url="/cms/ajax.php?module=eshop&controller=compare&action=ajaxaddtocompare&id="+id;
	if(changeText=="true"){
		url+="&changeText=true";
		$("#"+idCallback).load(url);
	}
	else{
		$("#"+idCallback+" span").load(url);
	}
}



function hideFormRowByJQ(obj){
	obj.parent().hide();
	obj.parent().prev("dt").hide();	
}

function showFormRowByJQ(obj){
	obj.parent().show();
	obj.parent().prev("dt").show();	
}



function loadCmsScript(){
	$(".ajax_login_form").unbind("click");
	$(".ajax_login_form").click(function(){
		url=URL_AJAX_LOGIN_FORM;
		tb_show("", url,"1");
	});
	
	$('.cartForm').ajaxForm({
		url: URL_CART_FORM,
		success:  function(formData, jqForm, options) { 
			    $("#cartAddData").remove();
				$("body").append('<div id="cartAddData" style="display:none;">'+formData+'</div>');
			    tb_show("","#TB_inline?modal=true&height=160&width=300&inlineId=cartAddData&tbClass=ajaxCartForm",1);			    
			    if(typeof cartFormLoaded =="function"){
			    	cartFormLoaded();
			    }
			    return true; 
			} 
		
	}); 


	
	
	$(".ajaxForm").each(function(){
		targetForm="#"+$(this).attr("rel");
		$(this).ajaxForm({
			target:targetForm
		});
	});
	

	
	
	$(".confirm_submit").unbind("click");
		
	$(".confirm_submit").click(function(){
		q=$(this).attr("alt");
		if(q==""){
			//alert("empty");
			return true;
		}
		else
		{
			if(confirm(q)){ return true; }
			else { return false; }
		}
		
	});

	
	
	$("a.thickbox").unbind("click");
	tb_init('a.thickbox');//pass where to apply thickbox
	
	
	$(".ajaxThickbox").unbind("click");
	$(".ajaxThickbox").click(function(){
		url=$(this).attr("href");
		tb_show("", url,"1");
		return false;
	});
	
	
	
	$(".ajaxLoad").unbind( "click" )
	$(".ajaxLoad").click(function(){
		obj = $(this);
		var dataPost = {
				"name" : $(this).attr("name"),
				"alt" : $(this).attr("alt"),
				"title" : $(this).attr("title"),
				"id" : $(this).attr("id")
		};
		$.ajax({
			   type: "POST",
			   url: $(this).attr("href"),
			   data: dataPost,
			   success: function(msg){
			     obj.html(msg);
			   }
		});
		return false;
	});
	
	$(".ajaxLoadGet").unbind( "click" )
	$(".ajaxLoadGet").click(function(){ 
		if($(this).hasClass("confirm_submit")){
			if(!confirmLink($(this).attr("alt"))){
				return false;
			}
		}
		href=$(this).attr("href");
		if($(this).attr("rel")!=""){
			$("#"+$(this).attr("rel")).load(href);
		}
		else{
			$(this).load(href);
		}
		return false;
	});	
	
	$(".autoTable tr:odd").addClass("odd");
	$(".autoTable tr:even").addClass("even");

	
	$(".ajaxLoadTb").unbind( "click" )
	$(".ajaxLoadTb").click(function(){ 
		if($(this).hasClass("confirm_submit")){
			if(!confirmLink($(this).attr("alt"))){
				return false;
			}
		}
		href=$(this).attr("href");
		$("#TB_ajaxContent").load(href);
		return false;
	});	
	

	$('.ajaxFormTb').ajaxForm({
		method: "post",
		success:  function(formData, jqForm, options) { 
			obj=$("#TB_ajaxContent");
			obj.html(formData);
			} 
		
	}); 

	

	$(".dLoader").dLoader();
	
}


function closeTb(){
	tb_remove(); 
}


function ajaxLoadTo(obj,target){
	try{
		href=obj.attr("href");
		$.get(href, function(data) {
		  target.html(data);
		});
	}
	catch(e){
		alert("Error ".e.description());
	}
	return false;
}



function addBookmark(){
	if (document.all && !window.opera) 
	  { 
	    window.external.AddFavorite(addUrl,addTitle); 
	    return false; 
	  } 
	  else if (window.opera && window.print) 
	  { 
	    linkObj.title = addTitle; 
	    return true; 
	  } 
	  else if ((typeof window.sidebar == 'object') && (typeof window.sidebar.addPanel == 'function')) 
	  { 
	    if (window.confirm('Prida� ob��ben� str�nku ako nov� panel?')) 
	    { 
	      window.sidebar.addPanel(addTitle,addUrl,''); 
	      
	    }
		return false; 
	  } 
	  window.alert('Pre potvrdenie stla�te CTRL-D,\nstr�nka bude pridan� k va�im ob��ben�m odkazom.'); 
	  return false; 
}

function sendLink(){
	tb_show("",URL_SEND_LINK,1);
	return false;
}

function printSite(){
	window.open(URL_PRINT_LINK,"print");
	return false;
}



/**
Functions
*/

function is_string (mixed_var){
    // Returns true if variable is a Unicode or binary string  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/is_string
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: is_string('23');
    // *     returns 1: true
    // *     example 2: is_string(23.5);
    // *     returns 2: false
    return (typeof( mixed_var ) == 'string');
}


/**
 * ako empty phpckova 
 * @return bool
 */
function empty (mixed_var) {
    var key;
    if (mixed_var === "" ||
        mixed_var === 0 ||
        mixed_var === "0" ||
        mixed_var === null ||
        mixed_var === false ||
        typeof mixed_var === 'undefined'
    ){
        return true;
    }
 
    if (typeof mixed_var == 'object') {
        for (key in mixed_var) {
            return false;
        }
        return true;
    }
 
    return false;
}


jQuery.fn.exists = function(){return jQuery(this).length>0;}



function addEmail(idForm){
	$.ajax({
		url: URL_ADDEMAIL_FORM,
		method: 'GET',
		data: {'email':$("#"+idForm).val()},
		success:  function(formData, jqForm, options) { 
			    $("#newsletterEmailAdd").remove();
				$("body").append('<div id="newsletterEmailAdd" style="display:none;">'+formData+'</div>');
			    tb_show("","#TB_inline?height=160&width=300&modal=true&inlineId=newsletterEmailAdd",1);			    
			    return true; 
			} 
		
	}); 
}









function in_array (needle, haystack, argStrict) {
    // Checks if the given value exists in the array  
    // 
    // version: 911.718
    // discuss at: http://phpjs.org/functions/in_array
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: vlado houba
    // +   input by: Billy
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
    // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
    // *     returns 2: false
    // *     example 3: in_array(1, ['1', '2', '3']);
    // *     returns 3: true
    // *     example 3: in_array(1, ['1', '2', '3'], false);
    // *     returns 3: true
    // *     example 4: in_array(1, ['1', '2', '3'], true);
    // *     returns 4: false
    var key = '', strict = !!argStrict;
 
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }
 
    return false;
}


/**
 * js equivalent of php print_r
 * @param arr
 * @param level
 * @return
 */
function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}



function urlencode (str) {
    // URL-encodes string  
    // 
    // version: 911.718
    str = (str+'').toString();
        // Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
    // PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
    return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
                                                                    replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}



function strlen (string) {
    // Get string length  
    // 
    // version: 1004.1212
    // discuss at: http://phpjs.org/functions/strlen
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Sakimori
    // +      input by: Kirk Strobeck
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +    revised by: Brett Zamir (http://brett-zamir.me)
    // %        note 1: May look like overkill, but in order to be truly faithful to handling all Unicode
    // %        note 1: characters and to this function in PHP which does not count the number of bytes
    // %        note 1: but counts the number of characters, something like this is really necessary.
    // *     example 1: strlen('Kevin van Zonneveld');
    // *     returns 1: 19
    // *     example 2: strlen('A\ud87e\udc04Z');
    // *     returns 2: 3
    var str = string+'';
    var i = 0, chr = '', lgth = 0;
 
    var getWholeChar = function (str, i) {
        var code = str.charCodeAt(i);
        var next = '', prev = '';
        if (0xD800 <= code && code <= 0xDBFF) { // High surrogate (could change last hex to 0xDB7F to treat high private surrogates as single characters)
            if (str.length <= (i+1))  {
                throw 'High surrogate without following low surrogate';
            }
            next = str.charCodeAt(i+1);
            if (0xDC00 > next || next > 0xDFFF) {
                throw 'High surrogate without following low surrogate';
            }
            return str.charAt(i)+str.charAt(i+1);
        } else if (0xDC00 <= code && code <= 0xDFFF) { // Low surrogate
            if (i === 0) {
                throw 'Low surrogate without preceding high surrogate';
            }
            prev = str.charCodeAt(i-1);
            if (0xD800 > prev || prev > 0xDBFF) { //(could change last hex to 0xDB7F to treat high private surrogates as single characters)
                throw 'Low surrogate without preceding high surrogate';
            }
            return false; // We can pass over low surrogates now as the second component in a pair which we have already processed
        }
        return str.charAt(i);
    };
 
    for (i=0, lgth=0; i < str.length; i++) {
        if ((chr = getWholeChar(str, i)) === false) {
            continue;
        } // Adapt this line at the top of any loop, passing in the whole string and the current iteration and returning a variable to represent the individual character; purpose is to treat the first part of a surrogate pair as the whole character and then ignore the second part
        lgth++;
    }
    return lgth;
}


function reload(){
	
	href=location.href;
	if(href.indexOf("#")>0){
		href=href.substring(0,href.indexOf("#"));
	}
	location.href=href;
	return false;
}


(function ($) {
$.fn.vAlign = function() {
	return this.each(function(i){
	var h = $(this).height();
	var oh = $(this).parent().height();
	var mt = ((oh - h)) / 2;	
	//$(this).parent().css("position", "relative");	
	$(this).css("margin-top", mt + "px");	
	//$(this).css("top", "50%");
	//$(this).css("position", "absolute");	
	});	
};
})(jQuery);







(function($){
	$.fn.dLoader = function(options){
		  
		// default configuration properties
		var defaults = {			
			image:'/cms/styles/images/loadingAnimation.gif',
			ajaxStart:true,
			ajaxClose:true,
			backgroundColor : "black",
			backgroundOpacity : 0.7,
			transparentImage : false,
			fadeSpeed : 300
		}; 
		
		var options = $.extend(defaults, options);  
				
		this.each(function() {  
			var obj = $(this);
			obj.bind("mouseup",function(){ 
				createLoader(); 
			});
		});
		
		function createLoader(){
			clearLoader();
			var appendObject="body";
			if(options.transparentImage){
				appendObject=".dLoaderOverlay";
			}
			
			
			$("<div class=\"dLoaderOverlay\" style=\"height: 100%;left: 0;position: fixed;top: 0;width: 100%;z-index: 998;background:"+options.backgroundColor+";\"></div>")
				.appendTo("body")
				.css("opacity",0)
				.fadeTo(options.fadeSpeed,options.backgroundOpacity);
			$("<img class=\"dLoaderImage\" style=\"position: fixed;top: 0;left:0;z-index: 999;\" src=\""+options.image+"\" />")
				.appendTo(appendObject).css("opacity",0);
				
				$(".dLoaderImage").load(function(){
					height=$(".dLoaderImage").height();
					width=$(".dLoaderImage").width();
					
					$(".dLoaderImage")
						.css('left',Math.round(($(".dLoaderOverlay").width()-$(".dLoaderImage").width())/2)+"px")
						.css('top',Math.round(($(".dLoaderOverlay").height()-$(".dLoaderImage").height())/2)+"px")
						.css('opacity',1);
					//console.log($(".dLoaderOverlay").width()+"<br>");
					
				});
				
				
			$(".dLoaderOverlay").click(clearLoader);	
				
				if(options.ajaxClose){
					$(document).ajaxComplete(function(event,request, settings){
						clearLoader();
					});
				}
				
				
		}
		function clearLoader(){
			$(".dLoaderOverlay").remove();
			$(".dLoaderImage").remove();
		}
		
	}	
})(jQuery);


var delphi={}
delphi._modules = {
		'jquery.router': {
			'1':{
				'src': "/cms/scripts/jquery/jquery.router-0.4.6.js"
			}
		},
		'jquery.scrollto': {
			'1':{
				'src': "/cms/scripts/jquery/jquery.scrollTo-1.4.2-min.js"
			}
		},
		'jquery.easyslider': {
			'1':{
				'src': "/cms/scripts/jquery/easySlider1.7.js"
			}
		}
}


delphi.load = function(moduleName, moduleVersion,callBack){
	exists=false;
	module=this.getModule(moduleName,moduleVersion);
	if(module){
		create=true;
		exists=false;
		scripts=document.getElementsByTagName("head")[0].getElementsByTagName("script");
		for(var i in scripts)
		{
			if(typeof scripts[i] == "object"){
				//console.log(scripts[i].getAttribute("src")==module.src);
				if(scripts[i].getAttribute("src")==module.src){
					create=false;
					exists=true;
				}
			}
		}
		if(create==true){
			var script = document.createElement("script");
			script.src = module.src;
			script.type = "text/javascript";
			script.onreadystatechange= function () {
			      if (this.readyState == 'complete') {
			    	  alert("loadComplete");
			      }
			}
			script.onload= function(){ 
				if(typeof callBack =="function"){
					callBack.call();
				} 
			};
			document.getElementsByTagName("head")[0].appendChild(script);
		}
	}
	if(exists && typeof callBack =="function"){
		callBack.call();
	}
	
	return false;
}

delphi.error = function(text){
	alert(text);
	return false;
}

delphi.getModule = function(moduleName,moduleVersion){
	if(this._modules[moduleName]!=undefined){
		module=this._modules[moduleName];
		if(moduleVersion>0){
			ver=moduleVersion;
		}
		else{
			ver=1;
		}
		if(module[ver]!=undefined){
			return module[ver];
		}
		return this.error("version "+ moduleVersion+" in module " + moduleName + " not exists");
		
	}
	else{
		return this.error("module" + moduleName + " not exists");
	}
}

delphi.log = {
		console:function(data){
			if(typeof console == "object"){
				console.log(data);
			}
		},	
		dump:function(data){
			alert(dump(data));
		}	
}

delphi.paginator={
		
		actualPage: 1,
		count: 0,
		countPages:0,
		perPage:6,
		
		paginator: null,
		
		setPage: function(page){
			alert(page + " / "+this.perPage );
		},
		getPage: function(page){
			return this.actualPage;
		},
		setPerPage: function(num){
			this.perPage = num;
		},
		getPerPage: function(){
			return this.perPage;
		},
		setCount:function(num){
			this.count=num;
		},
		getCount:function(){
			return this.count;
		},
		getPages:function(){
			return Math.ceil(this.getCount()/this.getPerPage());
		},
		addPage:function(step){
			page=this.getPage()+step;
			if(page>0 && page<=this.getPages()){
				return this.setPage(page);
			}
		}
		
}



