Tools = {
   _baseServiceImagePath: '/public/images/service/',
   _loaderProgress: 'ajaxloadergrey.gif',
   
   setStyle: function(stylename)
   {
      Tools._loaderProgress = stylename + '.gif';
   },
   
   replaceLoader: function(elem, text)
   {
        text = text?text+"<br />":"";
        elem.html("<div id='loaderimage'  style='width: 100%; text-align:center; padding-top: 20px; '>"+ text +"<img src='"+ Tools._baseServiceImagePath + Tools._loaderProgress +"'></div>");
   },
   
   addLoaderTop: function(elem, text)
   {
        text = text?text+"<br />":"";
        elem.prepend("<div id='loaderimage' style='width: 100%; text-align:center; padding-top: 20px; '>"+ text +"<img src='"+ Tools._baseServiceImagePath + Tools._loaderProgress +"'></div>");
      
   },
   
   removeLoader: function()
   {
       $('#loaderimage').remove();
   },
   
   addLoaderBottom: function(elem, text)
   {
        text = text?text+"<br />":"";
        elem.append("<div id='loaderimage' style='width: 100%; text-align:center; padding-top: 20px; '>"+ text +"<img src='"+ Tools._baseServiceImagePath + Tools._loaderProgress +"'></div>");
   },
   
   enableMainLoader: function()
   {
       $('#mainloader').html("<div style='width: 100%; text-align: center; margin: 20px;'><img src='/public/images/service/ajaxloaderwhite.gif'><br />идет загрузка...</div>");
   },
   
   disableMainLoader: function()
   {
       $('#mainloader').text('');
   },
   
   enableTinyMCE: function()
   {
        $('textarea:tinymce').each(function () { $(this).tinymce().remove(); });
  		$('textarea').tinymce(
		{
			// Location of TinyMCE script
			script_url : '/public/js/tiny_mce/tiny_mce.js',

			// General options
			theme : "advanced",
			plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

			// Theme options
			theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,preview",
			theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,link,unlink,anchor,image,cleanup,code,|,forecolor,backcolor,|,charmap,emotions,iespell,media,advhr,fullscreen",
			theme_advanced_buttons3 : "",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location : "bottom",
			theme_advanced_resizing : true
		}  
  		);   
   },
   
   enableDatePicker: function(elem, options)
   {
   	   var options = !!options?options:{dateFormat: 'dd.mm.yy'};
       if(elem){
          elem.datepicker(options);
       }else{
          $(".datepicker").datepicker(options);
       }
   },
   
   enableTooltipBox: function(elem)
   {
	   elem.tooltip({ 
		    track: true, 
		    delay: 0, 
		    showURL: false, 
		    opacity: 1, 
		    fixPNG: true, 
		    showBody: " ^ ", 
		    extraClass: "pretty", 
		    top: -15, 
		    left: 5
		  });    
   }
}



Reward = {
   rewards: [],

   setStatus: function(obj)
   {
        Reward._setRange(obj);
        if(Reward._isShowButton()){
           $('#rewardbutton').show('slow');
        }
   },
   
   send: function()
   {
        Reward.prepareData();
        Tools.setStyle('ajaxloadercircle');
        Tools.replaceLoader($('#rewardbutton')); 
        $.jsHttpRequest({
             url: $('#rewardcontainer').attr('path'),
             data: {'data': Reward.rewards},
             onReady: function(result, text) {
                 $('#rewardcontainer').html('<b>Спасибо. Нам очень важно Ваше мнение.</b>');
                 $.cookie('ifSendOpinion', true, { expires: 1, path: '/' });
             }
         });       
   },
   
   prepareData: function()
   {
       $('.reward').each(
          function(x){
             Reward.rewards[x] = {id: $(this).attr('id'), label: $(this).children('span').text(), reward: $(this).attr('reward')};
          }
       );
       return Reward.rewards;
   },   
   _setRange: function(obj)
   {
      var reward = $(obj).attr('reward');
      var containerID = $(obj).parent('div').attr('id');
      $('#'+containerID+' img').each(
         function(x){
              if($(this).attr('reward') <= reward ){
                 $(this).attr('src', '/public/images/service/star_on.gif');
              }else{
                 $(this).attr('src', '/public/images/service/star_off.gif');
              }  
         }
      );
      $(obj).parent('div').attr('reward', reward);
   },
   
   _isShowButton: function()
   {
       var status = true;
       $('.reward').each(
          function(x){
             if($(this).attr('reward') < 1){
                status = false;
             }
          }
       );
       return status;
   }
}

ContentWindow = {
    _defX: 700,
    _defY: 450,
    _minTopOffset: 130,

    show: function(content, params, callback)
    {
    	$.colorbox.close();
		if(!params || typeof(params.dontHideLookbook) == 'undefined') { 
		   Lookbook.hide();
		   $('.close-button').unbind();
		}       	
		$('.close-button').click(function(){ContentWindow.hide();});
        $('div#main-window').hide();

        Faq.closeForm();

        if(!!params && !!params.target){
        	params.target.html(content);
        }else{
            //console.log($('div#main-window .container div.content'));
	        $('div#main-window .container').html('<div id="jscroll"><div class="content">' + content + '</div></div>');
        }
        if(!!params && !!params.jscrollWidth) $('#jscroll').css('width', params.jscrollWidth);
        if(!!params && !!params.jscrollHeight) $('#jscroll').css('height', params.jscrollHeight);
        $('div#main-window').width(ContentWindow._defX).css('margin-left', '-' + (ContentWindow._defX / 2) + 'px' ).height(ContentWindow._defY).css('margin-top', '-' + (ContentWindow._defY / 2) + 'px' );
        if(!!params && !!params.width) $('div#main-window').width(params.width).css('margin-left', '-' + (params.width / 2) + 'px' );
        if(!!params && !!params.height) $('div#main-window').height(params.height).css('margin-top', '-' + (params.height / 2) + 'px' );
        if (typeof(callback) == 'function') {
            callback($('div#main-window'));
        }
        $('div#main-window').fadeIn(600);
        var position = $('div#main-window').offset();
        if(position.top < ContentWindow._minTopOffset) {
            if($.browser.msie || $.browser.safari){
            	$('div#main-window').css('margin-top', '-118' - position.top + 'px');
            }else{
            	$('div#main-window').offset({top: ContentWindow._minTopOffset});
            }
        }
 	   Tools.enableTooltipBox($('.tooltip-box'));	   
    },
    
    hide: function()
    {
    	$('div#main-window').hide();
    	$('#authorizationform').fadeOut(600);
		$('.backfon').hide();   
		$('div#main-window div.control').hide(); 
    },
    
    showDealerLoginForm: function()
    {
        ContentWindow.hide();
        $('#authorizationform').fadeIn(600); 
    },
    
    openPopUp: function(href, width, height)
    {
        window.open(href,'new','width=' + width + ',height=' + height + ',toolbar=0,scrollbars=yes');
    },
    
    loadHref: function(href, params, jsparams)
    {
        $.jsHttpRequest({
             url: href,
             data: !!params?params:null,
             onReady: function(result, text) {
                 Model.removeCatalog();
                 ContentWindow.show(text, jsparams, ContentWindow.reinit );
			     Menu.closeAll();
			     Model.closeSearchWindow();
			     $('#jscroll .window-href').click(
			         function(){
			             ContentWindow.loadHref($(this).attr('href'), null, $(this).hasClass('with-image') ? {'jscrollWidth' : '400px' , 'jscrollHeight' : '450px' , 'height': 480, 'target' : $('div#main-window .container')} : null);
			             return false;
			         }
			     ); 
			     				             
             }
         });    	
    },
    

    
    initialize: function()
    {
	     $('.window-href').click(
	         function(){
	             ContentWindow.loadHref($(this).attr('href'), null, $(this).hasClass('with-image') ? {'jscrollWidth' : '400px' , 'jscrollHeight' : '450px' , 'height': 480, 'target' : $('div#main-window .container')} : null);
	             return false;
	         }
	     );    
	     $('.window-href-catalog').click(
	         function(){
	             Model.loadCatalog($(this).attr('href'));
	             return false;
	         }
	     );    
	     
    	 $('.window-href-model').click(
	         function(){
	             Model.loadItem($(this).attr('href'));
	             return false;
	         }
	     ); 
	     
 
    },
    
    reinit: function()
    {
        $('#jscroll').jScrollPane({'scrollbarWidth': 10, 'showArrows': true});
        //$('.jScrollPaneContainer').css('width', 'auto');
    }
}

Gallery = {
   _interval: null,
   _arrowUp: false,
   _currentGalleryPosition: 0,
   _currentGalleryStep: 1,
   _currentCatalogGalleryStep: 3,
   _currentGalleryBigStep: 30,
   _currentGalleryPause: 100,
   _currentGalleryCatalogPause: 10,
   _currentIterator: 0,
   _flag: 'direct',
   _catalogFlag: 'right',
   scrollGallery: function()
	{
	    // console.log($('div.gallery ul:visible').width() , $('body').width());
	    if($('div.gallery ul:visible').width() <= $('body').width()) {
	       $('div.gallery ul:visible').css('left', ($('body').width() - $('div.gallery ul:visible').width())/2);
	       return;
	    }else{
		    var of = $('div.gallery ul').offset();
			if($('div.gallery ul').width() - $('body').width() + of.left <=0 ){
			   Gallery._flag = 'reverse'; 
			}
			if(Gallery._flag == 'reverse' && of.left >= 0 ){
			   Gallery._flag = 'direct';
			}
			if(Gallery._flag == 'direct'){
				Gallery._currentGalleryPosition -= Gallery._currentGalleryStep ;
			}else{
				Gallery._currentGalleryPosition += Gallery._currentGalleryStep;
			}
			
		    $('div.gallery ul').css('left', Gallery._currentGalleryPosition + 'px');
	    }
	    
	},
	
	showImage: function(elem)
	{
		var img = $('<img>');
		img.attr('src', $(elem).children().attr('src').replace(/\/small\//, '/big/')).attr('height', '520');
		// console.log($(elem).attr('wt'));
		ContentWindow.show(img, {'target' : $('div#main-window .container'), 'width': parseInt($(elem).attr('wt')), 'height': parseInt($(elem).attr('ht'))+20});
		$('.backfon').show();
		
	},
	
	seekLeft: function()
	{
		Gallery._flag = 'direct';
	   if($('div.gallery ul:visible').width() <= $('body').width()) return;
	   
	   var of = $('div.gallery ul').offset();
	   
	   
	   if($('div.gallery ul').width() - $('body').width() + of.left <= 0){
		   Gallery._flag = 'reverse';
		   Gallery._currentGalleryPosition = $('body').width() - $('div.gallery ul').width();
	   }else{
		   Gallery._flag = 'direct';
		   Gallery._currentGalleryPosition -= 100;
	   }



	   Gallery._currentGalleryPosition -= 100;
	}, 
	
	seekRight: function()
	{
	   if($('div.gallery ul:visible').width() <= $('body').width()) return;
	   if(Math.abs( Gallery._currentGalleryPosition ) <= 100){
		   Gallery._flag = 'direct';
		   Gallery._currentGalleryPosition = 0;
	   }else{
		   Gallery._flag = 'reverse';
		   Gallery._currentGalleryPosition += 100;
	   }
	},
	
	enableMove: function()
	{
		clearInterval(Gallery._interval);
		Gallery._interval = setInterval( 'Gallery.scrollGallery()', Gallery._currentGalleryPause);
        $('.leftarrow').
	        mousedown(function(){
	           Gallery._currentGalleryStep = Gallery._currentGalleryBigStep; 
	           Gallery._flag = 'direct';  
	           return false;
	        }).
	        mouseup(function(){
	           Gallery._currentGalleryStep = 1; 
	           Gallery._flag = 'direct';  
	           return false;
	        }).
	        click(function(){});
        $('.rightarrow').
	        mousedown(function(){
	           Gallery._currentGalleryStep = Gallery._currentGalleryBigStep; 
	           Gallery._flag = 'reverse';  
	           return false;
	        }).
	        mouseup(function(){
	           Gallery._currentGalleryStep = 1; 
	           Gallery._flag = 'reverse'; 
	           return false;
	        }).
	        click(function(){});
	},
	
	disableMove: function()
	{
		clearInterval(Gallery._interval);
        
        $('.leftarrow').
	        mousedown(function(){}).
	        mouseup(function(){}).
	        click(function(){
	        	Gallery._moveCatalog('left');
	        });
        
        $('.rightarrow').
	        mousedown(function(){}).
	        mouseup(function(){}).
	        click(function(){
	        	Gallery._moveCatalog('right');
	        });		
	},
	
	_moveCatalogItem: function(  )
	{
		var of = $('div.gallery ul').offset();
		var bodyWidth = $('body').width();
		var intervalWidth = $('div.gallery ul img:first').width();
		//console.log(Math.abs(Gallery._currentIterator), $('body').width(), $('div.gallery ul').width() - $('body').width() + of.left, Gallery._flag, of.left);
	    if(Math.abs(Gallery._currentIterator) >= intervalWidth || 
	          (Gallery._flag == 'right' && $('div.gallery ul').width() - bodyWidth + of.left <=0) || 
	          (Gallery._flag == 'left' && of.left >= 0) )
	    {
	    	clearInterval(Gallery._interval);
	    	return;
	    } 
		
		if(Gallery._flag == 'right'){
			Gallery._currentGalleryPosition -= Gallery._currentCatalogGalleryStep ;
			Gallery._currentIterator -= Gallery._currentCatalogGalleryStep;
		}else{
			Gallery._currentGalleryPosition += Gallery._currentCatalogGalleryStep;
			Gallery._currentIterator += Gallery._currentCatalogGalleryStep;
		}
		// console.log(Gallery._currentGalleryPosition);
	    $('div.gallery ul').css('left', Gallery._currentGalleryPosition + 'px');
	},
	
    _moveCatalog: function( direction )
    {
    	var bdw = $('body').width() - $('.gallery .catalog').width();
    	if($('.gallery .catalog').position().left > 0) {$('.gallery .catalog').css('left', '0px'); Gallery._currentGalleryPosition = 0; return; }
    	if($('.gallery .catalog').position().left < bdw) {$('.gallery .catalog').css('left', bdw+'px'); Gallery._currentGalleryPosition = bdw; return;}
    	Gallery._currentIterator = 0;
		Gallery._flag = direction;
    	clearInterval(Gallery._interval);
		Gallery._interval = setInterval( 'Gallery._moveCatalogItem()', Gallery._currentGalleryCatalogPause); 
		return;
		
    	// старая реализация
    	var bdw = $('body').width() - $('.gallery .catalog').width();
    	if($('.gallery .catalog').position().left > 0) $('.gallery .catalog').css('left', '0px');
    	if($('.gallery .catalog').position().left < bdw) $('.gallery .catalog').css('left', bdw+'px');
    	
    	$('.gallery .catalog').animate(
    	    { left: (direction == 'right' ? '-' : '+') + '=' + ($('.gallery .catalog img:last').width() ) }, 
    	    { easing: "linear", duration: 2000, step: function(now, fx){   if( now < bdw || now >= 0 ) {   $('.gallery .catalog').stop();  } } }
    	    
    	 );
    	
    	return ;    	
	
    }
}

Lookbook = {
   show: function(type){
      $('.lookbook-container').prepend($('.lookbook-gallery'));
      Model.removeCatalog();
      $('.gallery .init').hide();
      $('.gallery').prepend($('.lookbook-' + type + '-gallery'));
      $('a[rel=lookbook-' + type + ']:first').click();
      ContentWindow.hide();
      Faq.closeForm();
      
   },
   
   hide: function()
   {
       $('.gallery .init').show();
       $('.lookbook-container').prepend($('.lookbook-gallery'));
   }
}
