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'>");
   },
   
   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)
   {
       if(elem){
          elem.datepicker({dateFormat: 'dd.mm.yy'});
       }else{
          $(".datepicker").datepicker({dateFormat: 'dd.mm.yy'});
       }
   },
   
   
   enableTooltipBox: function(elem)
   {
	   elem.tooltip({ 
		    track: true, 
		    delay: 0, 
		    showURL: false, 
		    opacity: 1, 
		    fixPNG: true, 
		    showBody: " ^ ", 
		    extraClass: "pretty", 
		    top: -15, 
		    left: 5
		  });    
   }   
}

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

    show: function(content, params, callback)
    {
		$('.close-button').click(function(){ContentWindow.hide();}); 
		if(!params || (typeof(params.dontCloseLookbook) == 'undefined')) { Lookbook.hide(); }
        $('div#main-window, div#main-window-opacity').hide();
        ContentWindow.hideBooklet();
        if(!!params && !!params.target){
        	params.target.html(content);
        }else{
	        $('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, div#main-window-opacity').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, div#main-window-opacity').width(params.width).css('margin-left', '-' + (params.width / 2) + 'px' );
        if(!!params && !!params.height) $('div#main-window, div#main-window-opacity').height(params.height).css('margin-top', '-' + (params.height / 2) + 'px' );
        if (typeof(callback) == 'function') {
            callback($('div#main-window'));
        }
        if($.browser.msie){
           $('div#main-window, div#main-window-opacity').show();
        }else{
           $('div#main-window, div#main-window-opacity').fadeIn(300);
        }   
        var position = $('div#main-window').offset();
        if(position.top < ContentWindow._minTopOffset) {
            if($.browser.msie){
            	//$('div#main-window, div#main-window-opacity').css('margin-top', '-118' - position.top + 'px');
            }else{
            	//$('div#main-window, div#main-window-opacity').offset({top: ContentWindow._minTopOffset});
            }
        }
  	   Tools.enableTooltipBox($('.tooltip-box'));	   
        
    },
    
    hide: function(dontShowBooklet)
    {
    	$('div#main-window, div#main-window-opacity').fadeOut(300);
        if(!dontShowBooklet) ContentWindow.showBooklet();
    	$('#catalog-list, #catalog-list-small').remove();
    },
    
    openPopUp: function(href, width, height)
    {
        window.open(href,'new','width=' + width + ',height=' + height + ',toolbar=0,scrollbars=yes');
    },
    
    showDealerLoginForm: function()
    {
        ContentWindow.hide();
        $('#authorizationform').fadeIn(300); 
    },
    
    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();
			     $('#jscroll .window-href').click(
			         function(){
			             ContentWindow.loadHref($(this).attr('href'), null, $(this).hasClass('with-image') ? {'jscrollWidth' : '400px' , 'jscrollHeight' : '450px' , 'height': 450, 'target' : $('div#main-window .container')} : null);
			             return false;
			         }
			     ); 				             
             }
         });    	
    },
    
	hideBooklet: function()
	{
		$('#book-container, #shadow-t').hide();        
	},
    
	showBooklet: function()
	{
		$('#book-container, #shadow-t').fadeIn(300);
	},
    
    initialize: function()
    {
	     $('.window-href').click(
	         function(){
	             ContentWindow.loadHref($(this).attr('href'), null, $(this).hasClass('with-image') ? {'jscrollWidth' : '400px' , 'jscrollHeight' : '450px' , 'height': 450, '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'), $(this).attr('catn'));
	             return false;
	         }
	     ); 
	     
 
    },
    
    reinit: function()
    {
        $('#jscroll').jScrollPane({'scrollbarWidth': 5, 'showArrows': false});
        //$('.jScrollPaneContainer').css('width', 'auto');
    }
}

Lookbook = {
	result: null,

	load: function(type)
	{
		Lookbook.hide();
        $.jsHttpRequest({
             url: '/index/lookbook/',
             data: { 'sex': type },
             onReady: function(result, text) {
                 
                 ContentWindow.hide();
                 ContentWindow.hideBooklet();
                 $('body').prepend(text);
                 $('#lookbook-list').show();
                 Lookbook.result = result.data;
			     $('.window-href-lookbook').click(
			         function(){
			             Lookbook.loadItem($(this).attr('key'));
			             return false;
			         }
			     ); 
			     Menu.closeAll();
			     if($('#lookbook-list .small-item').length > 8 || $('#catalog-list-small .model-small-item').length > 5 ) {
			        $('.larr, .rarr').show();
			     }
             }
         }); 	
	},
	
	hide: function()
	{
	   $('#lookbook-list').remove();
	   $('#lookbook-list-small').remove();
	},
	
    move: function( direction )
    {
        var frp = $('.couple:last').position().left - 3 * $('.couple:last').width();
        var wd = $('.couple:last').width();
        if(
           Math.abs(
            ($('#lookbook-list .container .items').position().left - $('.couple:last').width()) > frp && direction == 'right')
               || 
           ($('#lookbook-list .container .items').position().left >= 0 && direction !== 'right')
           ) return;
    	$('#lookbook-list .container .items').animate(
    	    { right: (direction == 'right' ? '+' : '-') + '=' + ($('#lookbook-list .container').width() + 8) }, 
    	    { duration: 2000, step: function(now, fx){ if(now > frp-wd+85 || now <= 0)  $('#lookbook-list .container .items').stop();   } }
    	 );
    },
    
    moveSmall: function( direction )
    {
        var frp = $('.small-item:last').position().left - 5 * $('.small-item:last').width();
        var wd = $('.small-item:last').width();
    	$('#lookbook-list-small .container .items').animate(
    	    { right: (direction == 'right' ? '+' : '-') + '=' + ($('#lookbook-list-small .container').width() + 3) }, 
    	    { duration: 2000, step: function(now, fx){ if(now > frp-wd+60 || now <= 0)  $('#lookbook-list-small .container .items').stop();  } }
    	 );
    },    
	
    loadItem: function(key)
    {
        // формируем блок показа
        var text = '<div id="lookbookinfo"><div class="rightcol"><div class="info">';
        $.each(Lookbook.result[key], function(key, value){
            if(!!value['id']){
            	text += '<a href="/catalog/model/id/' + value['id'] + '/newcol/" catn="' + value['articul'] + '" class="window-href-model">' + value['name'] + ' ' + value['articul'] + ' <br /><b>' + value['price'] + '</b>руб.</a><br /><br />';
            }else{
            	text += '<a href="#" onclick="return false;">' + value['name'] + ' ' + value['articul'] + '</a><br /><br />';
            }
        });
        text += '</div></div><div class="leftcol"><img src="/public/dimages/lookbook/big/' + key + '.jpg"   id="mainProductImage" /></div></div>';
         
         ContentWindow.show('<div class="catalog-content">' + text + '</div>', {'width' :  503 , 'height': 400, 'target' : $('div#main-window .container'), 'dontCloseLookbook' : true});
         $('#main-window, #main-window-opacity').css('margin-top', '-210px');
         ContentWindow.reinit();
         $('#lookbook-list').hide();
         $('#lookbook-list-small').show();
         $('#lookbook-list-small .small-item').removeClass('opacity60');
         $('.close-button').unbind().click(function(){ 
			$('div#main-window, div#main-window-opacity').fadeOut(600);
			$('#lookbook-list-small').hide();
			$('#lookbook-list').show();
          });
	     $('.window-href-model').click(
	         function(){
	              $('#lookbook-list-small').hide();
	             Model.loadItemLookbook($(this).attr('href'), $(this).attr('catn'), key);          
	             return false;
	         }
	     );  
        $('#lookbook-list-small .small-item').removeClass('opacity60');
        $('#lookbook-list-small a[key=' + key + ']').parent().addClass('opacity60');
	              
    } 
}
