// Cookie
jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){options=options||{};if(value===null){value='';options=$.extend({},options);options.expires=-1}var expires='';if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){var date;if(typeof options.expires=='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000))}else{date=options.expires}expires='; expires='+date.toUTCString()}var path=options.path?'; path='+(options.path):'';var domain=options.domain?'; domain='+(options.domain):'';var secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('')}else{var cookieValue=null;if(document.cookie&&document.cookie!=''){var cookies=document.cookie.split(';');for(var i=0;i<cookies.length;i++){var cookie=jQuery.trim(cookies[i]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break}}}return cookieValue}};

$(document).ready(function(){	  

    /* AJAX FORM */
   $('.search-form').each(function(){   
        if( $(this).hasClass('productListForm') ) {var productList=true}else{var productList=false}        
        var element = $(this);
        var sendData = '';
        $('form .form-list input:checked, form select, form textarea, form input.w-half', element).each(function(){
			sendData = sendData + '&' + $(this).attr('name') + '=' + $(this).val();
		});
		sendData = sendData.substr(1);
		sendData = sendData + '&btnParamSearchSubmit&ajax=true';
		
        setInterval(function(){
            
             dataActual = '';
             $('form .form-list input:checked, form select, form textarea, form input.w-half', element).each(function(){
                  dataActual = dataActual + '&' + $(this).attr('name') + '=' + $(this).val();
             });
             dataActual = dataActual.substr(1);
             dataActual = dataActual + '&btnParamSearchSubmit&ajax=true';
             
             if(dataActual != sendData && sendData != ''){
                sendData = dataActual;
                var url = "http://"+window.location.hostname;
                    url = url.replace(/^.*#/, '');
                if ( productList == true ){
                    $.ajax({
        			     type: "GET",
        			     url: url,
                         beforeSend: function(){
                         	$('.terms-sum', element).show();
						 	$('.terms-sum .number', element).html('<img src="/img/bg/ajax1.gif" alt=" "/>');
						 },
        			     data: sendData,
        			     
        			     success: function(xml){
        			             //alert("vvvv");
                          $('.terms-sum .number', element).text(xml);			     
        			     }
        		    });  
        		}
        		else{
                    $.ajax({
        			     type: "GET",
        			     url: url,
                         beforeSend: function(){
                         	$('.terms-sum', element).show();
						 	$('.terms-sum .number', element).html('<img src="/img/bg/ajax.gif" alt=" "/>');
						 },
        			     data: sendData,
        			     
        			     success: function(xml){
        			             //alert("vvvv");
                          $('.terms-sum .number', element).text(xml);			     
        			     }
        		    }); 
                }
             }
            
        
        }, 1500);
   });

    // Init pdBox
    $('.thickbox').pdBox({minWidth: 660});
 	
    function init(){
        $('.product-list').adjustHeights({
            elements : ['.status'],
            vAlign : 'center',
            adjust : false
        });
        
        $('.product-list .reset').adjustHeights({
            elements : ['h2 strong.name'],
            vAlign : 'top'
        });
        
        $('#product .product-object .img-box').adjustHeights({
            elements : ['.status'],
            vAlign : 'center',
            adjust : false
        });
        
        /* POSITIONED CORNER IE 6 RECALCULATE */
        $('.cor').css('position','absolute');
        
    }
    
    // SCROLL
    /*$('.buttons .r a').click(function(){
    	var $this = $(this);
		$('body, html').animate({scrollTop: $($this.attr('href')).offset().top}, 40000);
		return false;
	});*/
    
    // Volaní záložek
    $('.tabs-box').pdTabs({});
    
    // FONT SIZE
    $(document).fontSizeListener({
        element: '#mother',
        callFunction : function(){init()}
    });
    
    $('#home-params, #list-params, #dog-params').each(function(){
    	var $box = $(this),
    		$openBox = $('.box', $box),
    		$el = $('.moreParams a', $box);
    		
    	$('.hideDetails', $box).hide();
		
    	$el.click(function(){
    		if($openBox.is(':hidden'))
    		{
    		    $(this).hide();
    		    $('.hideDetails', $box).show();
    			$openBox.slideDown();	
    		}
    		else{
    		    $(this).hide();
    		    $('.showDetails', $box).show();
    			$openBox.slideUp();		
    		}
    		return false;
    	});
    	
    	
    });
    
    $('#product-list .search-form').each(function(){
    	$openBox1 = $('form', this);
        $('form, .hide', this).hide();
        var el = $(this);
        $('.hover-wrap', el).show();
        if ( $(this).hasClass('doHover') ){
        	$(this).hover(
              function () {
                $(this).addClass('makeHover').css('cursor', 'pointer');
              }, 
              function () {
                $(this).removeClass('makeHover').css('cursor', 'default');
              }
            );
        }
        $('a.show', this).click(function(){
    		if($openBox1.is(':hidden'))
    		{
    		    $(el).addClass('hover').removeClass('doHover');
	            $('form', el).slideDown();
	            $('.hide', el).show();
	            return false;
    		}
    		else{
    		    $(el).removeClass('hover').addClass('doHover');
	            $('form', el).slideUp();
	            $('.hide', el).hide();
	            return false;	
    		}
    		return false;
    	});
        $('.hide', this).click(function(){
            $(el).removeClass('hover').addClass('doHover');
            $('form', el).slideUp();
            $(this).hide();
            return false;
        });
    });
    
    // BUBLE
    $('.product-table-all .buble-reserved').hover(
        function(){
            $('.buble', this).show();  
        },
        function(){
            $('.buble', this).hide();
        }
    )
    
    // SEARCH BOX TEXT
	$('input#q').each(function(){
      	var btntext = $(this).attr('value');
      	$(this).focus(function(){
            text = $(this).attr('value');
            if( text == btntext ){
                $(this).attr('value', '');
            }
		}).blur(function(){
            var text2 = $(this).attr('value');
            if( text2 == '' || text2 == undefined ){
                $(this).attr('value', btntext);
            }
		});
	});
	
	$('.content table tr:even').addClass('even');
	
	// ADD FILE
	$('.addFile').each(function(){
		var el = $(this);
		var intID = $('input', this).attr('id');
		intID = intID.split('-')[1];
		intID = parseInt(intID);
		$('a', this).click(function(){
			if (intID < 20) {
				intID = intID + 1
				$('.int', el).append('<input id="file-'+intID+'" class="int-text" type="file" name="file-'+intID+'"/><br />')
				if (intID == 20) {
					$(this).hide();
				}
			}
			return false;
		});
	});
	
	
	
	// Brand sort
	$('#newReview, #home-params, #list-params, #detailForm, .car-filter, #dog-params').each(function(){
		
		var $this = $(this),
			$brand = $('#carBrandName', $this),
			$type =  $('#carType', $this);
			
		var copy = {
			$type: $type.clone()
		};
		
		var control = function(first){
			if($brand.find('option:first-child').is(':selected')){
				$type.html(copy.$type.html());
				$type.attr('disabled', true);
			}
			else{
				$type.attr('disabled', false);
				var c = $brand.find('option:selected').attr('class');
				$type.html('<option value="'+ copy.$type.find('option:first-child').val() +'">'+copy.$type.find('option:first-child').html()+'</option>' + copy.$type.find('optgroup.'+c).html());
				
				
				if(!first){ $type.focus();}
			}
		}
		
		$brand.each(function(){
			control(true);	
		}).bind('change', function(e){
			control(false);
		});
		
		
		
		//$('#carBrandName', this).parent().show(); 
		/*$('#carBrandName option').each(function(){
			if ( $(this).is(':selected') ) {
				var carClass = $(this).attr('class');
				$('#carType').each(function(){
					if ( $('#carBrandName option[value="empty"]').is(':selected') ) {
						$('#carType').attr('disabled', 'true');
					}
					$('optgroup', this).attr('label', '').hide();
					$('optgroup', this).each(function(){
						if ( $(this).attr('class') == carClass ) {
							$(this).show();
						}
					});
					
				});
			}			
		});
		$('#carBrandName option').click(function(){
			var carClass = $(this).attr('class');
			$('#carType').each(function(){
				$(this).attr('disabled', '');
				$('optgroup', this).hide();
				$('optgroup', this).each(function(){
					if ( $(this).attr('class') == carClass ) {
						$(this).show();
					}
				});
				$('option[value="empty"]', this).attr('selected', 'selected');
			});
		});*/
	});
		
	// In user section - review edit page - init AJAX textile preview/edit modes 
	$('.review-message .tab-2').click(function(){
		$('.review-message .tab-1').removeClass('active');
		$(this).addClass('active');
		var textareaHeight = $('#reviewWriter')[0].offsetHeight-9 + 'px';
		$('#reviewWriter').hide();	
		$('#reviewContent').show();
		$('#reviewContent .in').css('height', textareaHeight).addClass('loading').html('Nahrávám náhled…');
		$.post("/ajax/rpc_texy.php", { content: $('#reviewWriter textarea')[0].value },
			function(data)
			{				
				$('#reviewContent .in').removeClass('loading').empty();
				
				var fn = function(){ $('#reviewContent .in').html(data).css('overflow-y', 'auto'); }
				setTimeout(fn , 10);
			}
		);
		return false;
	});
	$('.review-message .tab-1').click(function(){
		$('.review-message .tab-2').removeClass('active');
		$(this).addClass('active');
		$('#reviewWriter').show();
		$('#reviewContent').hide();
		return false;
	});
	
	        
	//$('input.datepicker').datepicker({});
         
	// Currency change
	$('#product-detail').each(function(){
		$('.sort a').each(function(){
			var url = window.location.href;
			var url = url.split('#')[1];
			if (url==undefined){var url='';}
			var ahref = $(this).attr('href');
			$(this).attr('href', ahref+'&tab='+url);
		});		
		
		$('.tab-list a', this).click(function(){
			var url = window.location.href;
			var url = url.split('#')[1];
			$('.sort a').each(function(){
				var ahref = $(this).attr('href').split('#')[0].split('&')[0];
				$(this).attr('href', ahref+'&tab='+url);
			});	
		});
	});
	
	
	// HOMEPAGE BANNER	
	if ( !$.cookie('refvozybanner') ){
		$('.TB_overlay1')
			.before('<iframe id="TB_HideSelect" style="height:'+$('html').height()+'px;"></iframe>')
			.css({
				'display': 'block',
				'opacity': '0',
				'height': $('html').height()
			})
			.animate({
				'opacity': '0.5'
			}, 500, function(){
				$('#overlay-bnr')
					.css({
						'display': 'block',
						'top': '-385px'
					}).animate({
						'top': '100px'
					}, 1000).each(function(){
						var date = new Date();
	                    date.setTime(date.getTime() + (24 * 60 * 60 * 1000));
	                    $.cookie('refvozybanner', true, {expires: date});
						$('.closeBnr', this).click(function(){
							$('#TB_HideSelect').remove();
							$('#TB_overlay, #overlay-bnr').fadeOut();
							return false;
						});
					});		
			});
	}
	
	
	/****** LOAD TIME ******/    
    var time1 = 0,
    	time2 = 0,
        browser = null,
        version = null,
        endTime = new Date().getTime(),
        endTime2 = null,
        id = ($.cookie('PHPSESSID') + endTime);
    
    jQuery.each($.browser, function(i, val){
        if(val===true){
            if(i=='safari')
            {
                browser = /Chrome/.test(navigator.userAgent) ? 'chrome' : 'safari';
            }
            else
            {
                browser = i;
            }
        } 
    });
    
    time1 = endTime - loadTime;
    $.ajax({
       type: 'POST',
	   url: '/ajax/loadtime',
	   data: 'id='+(id)+'&time1='+time1+'&time2='+time2+'&servertime='+servertime+'&browser='+browser+'&version='+$.browser.version+'&userAgent='+navigator.userAgent
    });
    
    function loadImages(i){
        var test = i,
            not = 0;
        
        jQuery.each(document.images, function(index, img){
            if(!img.complete){
                not++;
            }
        });
        if(not>0 && test<10)
        {
            setTimeout(function(){loadImages(test+1)}, 200)
        }
        else
        {
            endTime2 = new Date().getTime();
            
			time2 = endTime2 - loadTime;
            $.ajax({
               type: 'POST',
        	   url: '/ajax/loadtime',
        	   data: 'id='+(id)+'&time1='+time1+'&time2='+time2+'&servertime='+servertime+'&browser='+browser+'&version='+$.browser.version+'&userAgent='+navigator.userAgent+'&unloadImg='+not
            }); 
        }
    }
    loadImages(0)
	  
});
