/*
взять DOM-элемент по id
*/
function $(id)
{
    return document.getElementById(id);
};

/*
создать DOM-элемент (таг)
*/
function $$(tag)
{
	return document.createElement(tag);
};

/*
удалить DOM-элемент (таг) и освободить память
*/
function $_(elem)
{
    if (elem && elem.parentNode)
    {
        var p = elem.parentNode;
        p.removeChild(elem);
        delete(elem);
    }
};
/*
hash навигация
*/
function naviHash(param){
	var t = this;
	window.cache = [];
	var p ={
		contentBlock:'',	// класс или ИД блока в который падает контент (#press_content)
		contentUrl:'',		// путь до получения страницы (/intro/press/)
		defaultPage:'',		// страница по умолчанию (#press_printed_publications_2009_page)
		changeImg: false,	// если надо менять картинку как в туре по сайту то true
		navBlockLi:'',		// селектор блока с меню
		navBlockLi2:'',		// селектор блока с меню2 в котором надо сделать ссылки активными
		setActiv: false,	// если надо сделать активными ссылки во втором меню
		menu_header:''		// селектор заголовка меню
	};
	// запускной метод
	this.start = function(){
		jQuery(document).ready(function() {
		    jQuery(p.navBlockLi).click( 
		            function () {
		                if(jQuery(this).is(p.menu_header)) return false;
		                var current_el_id = jQuery(this).attr('id');

		                if(jQuery(this).is('.active_li') || jQuery(this).is('.active_li_last')) return false;
		                
		                jQuery(p.navBlockLi).removeClass('active_li');
		                jQuery(p.navBlockLi).removeClass('active_li_last');
		                
		                if(jQuery(this).is('.last_dl')) jQuery(this).addClass('active_li_last');
		                else jQuery(this).addClass('active_li');
		                
		                
		                
		                //если меняем картинку
		                if(p.changeImg){
		                	if(jQuery('#side_menu li img').is('.img_active_helper_class'))
		                    {
				                var img_src = jQuery(p.navBlockLi+' img.img_active_helper_class').attr('src').split('_g');
				                jQuery(p.navBlockLi+' img.img_active_helper_class').attr('src', img_src[0]+img_src[1]);
				                jQuery(p.navBlockLi+' img.img_active_helper_class').removeClass('img_active_helper_class');
		                    }
			                jQuery('#'+current_el_id+' img').addClass('img_active_helper_class');
			                img_src = jQuery('#'+current_el_id+' img').attr('src').split('.');
			                jQuery('#'+current_el_id+' img').attr('src', img_src[0] + '_g.' + img_src[1]);
		                }
		                
		              //если надо сделать активными ссылки во втором меню
		                if(p.setActiv){
		                	
		                	//снимаем активность с side меню
		                    jQuery(p.navBlockLi2).removeClass('active_li');
		                    jQuery(p.navBlockLi2).removeClass('active_li_last');
		                    if(jQuery(p.navBlockLi2+' img').is('.img_active_helper_class'))
		                    {
		                        var img_src = jQuery(p.navBlockLi2+' img.img_active_helper_class').attr('src').split('_g');
		                        jQuery(p.navBlockLi2+' img.img_active_helper_class').attr('src', img_src[0]+img_src[1]);
		                        jQuery(p.navBlockLi2+' img.img_active_helper_class').removeClass('img_active_helper_class');
		                    }
		                    
		                }
		                
		                var url = jQuery(this).attr('id').split('_page')[0];
		                var page_name = jQuery(this).attr('id').split('_page')[0];
		                window.location.hash = url;
		                if(typeof(window.cache[page_name]) == 'undefined')
		                {
		                    jQuery.post(p.contentUrl,
		                    	    {
		                               is_ajax: 1,
		                               content_page: page_name
		                            },
		                            function(data_json) {
		                                var data = eval( "(" + data_json + ")" );
		                                window.cache[page_name] = data_json
		                                jQuery(p.contentBlock).html(data);
		                            });
		                }
		                else
		                {
		                	var data = eval( "(" + window.cache[page_name] + ")" );
		                    jQuery(p.contentBlock).html(data);
		                }
		                return false;
		            });

		    var url = '';
		    var is_ajax = 0;
		    var page = window.location.hash;
		    //esli s ankorom
		    var pAncor = page.split('/');
		    if(pAncor[1]) {
		    	t.pageAncor(pAncor[0],pAncor[1],page);
		    	return false;
		    }
		    
		    if(page != '') {
		        if(!jQuery(page+'_page').click()[0]) page = '';
		    }
		    if(page == '') jQuery(p.defaultPage).click();
		    jQuery(t.init);
		    
		});
	};

	// init метод истории
	this.init = function(){
        jQuery(window).history(function( e, ui ){
        	if(ui != undefined)jQuery('#'+ui.value+'_page').click();
        });
    };
    
	// init вывод если есть анкор в hash
	this.pageAncor = function (page,ancor,pa){
    	var page = page.split('#')[1];
    	
    	jQuery.post(p.contentUrl,
        	    {
                   is_ajax: 1,
                   content_page: page
                },
                function(data) {
                    if(data){
                    	window.cache[page] = data
	                    jQuery(p.contentBlock).html(data);
	                    window.location.hash = pa;
                    } else {
						page='';
                    }
                },"json");
        return false;
    };
    
	// установить новые параметры
	this.setParam = function(param){
		p = t.array_merge(p,param);
		t.start();
	};
	
	// склеить параметры
	this.array_merge = function()
	{    
	     var res = {};
	     for (var i = 0; i < arguments.length; i++)
	         for (id in arguments[i]) 
	        	 if (typeof(arguments[i][id])=='object') 
	        		 res[id]=array_merge(res[id], arguments[i][id]); 
	        	 else 
	        		 res[id]=arguments[i][id];
	     return res;
	 };


	/* init class */
	t.setParam(param);
};
/*
String: var a = trim(b);
*/
function trim(s)
{
    s = s.replace(/^[\s\n]+/g, '');
    s = s.replace(/[\s\n]+$/g, '');
    return s;
};

/*
Скрыть пустой элемент списка
*/
function collapseEmptyLi(cid)
{
    var c = $(cid);
    if (!c) return;
    c.style.display = 'none';
    var el = c.getElementsByTagName('LI');
    var len = el.length, div_el, a_el;
    for(var i=0;i<len;i++)
    {
    	div_el = el[i].getElementsByTagName('div');
    	
    	if (typeof(div_el[1])!='undefined' && trim(div_el[1].innerHTML).length==0)
  		{
   			el[i].style.display = 'none';    		
    	}
    	
    	else
    	{
    		a_el = div_el[1].getElementsByTagName('a');
    		if (typeof(a_el[0])!='undefined' && trim(a_el[0].innerHTML).length==0)
    			el[i].style.display = 'none';
    	}
    }
    c.style.display = 'block';
};

function setCookie(name,value,expires,path,domain,secure)
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
		//expires = expires * 1000 * 60 * 60 * 24;
		expires = expires * 1000;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
};


function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
};

// this deletes the cookie when called
function deleteCookie(name,path,domain)
{

	if (getCookie(name))
		document.cookie = name + "=" +
		((path) ? ";path=" + path : "") +
		((domain) ? ";domain=" + domain : "" ) +
		";expires=Thu, 01-Jan-1970 00:00:01 GMT";

};

function comboDays(day_combo, month_combo, year_combo)
{
    var day = $(day_combo).value;
    var month = $(month_combo).value;
    $(day_combo).innerHTML = '';
    $(day_combo).options[0] = new Option('', 0);
    if (month>=0 && month<=12)
    {
        var end = 0;
        switch(month)
        {
            case '0': case '1': case '3': case '5': case '7': case '8': case '10': case '12':
               end = 31;
            break;
            case '4': case '6': case '9': case '11':
               end = 30;
            break;
            case '2':
                var yy = parseInt($(year_combo).value)%4;
                if (yy==0 && $(year_combo).value!='1900')
                {
                   end = 29;
                }
                else
                {
                   end = 28;
                }
            break;
        }
        for (var i=1; i<=end; i++)
        {
            if(i==day) $(day_combo).options[i] = new Option(i, i, false, true);
            else $(day_combo).options[i] = new Option(i, i, false, false);
        }
    }
};

/*
String: var a = trim('<b>something</b>'); // s = 'something';
*/
function stripTags(s)
{
    return s.replace(/(<[^>]+>)/g,'');
};

/*
 * Encode string in BASE64
 */
function base64_encode( data ) {	// Encodes data with MIME base64
	// 
	// +   original by: Tyler Akins (http://rumkin.com)
	// +   improved by: Bayron Guevara

	var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	var o1, o2, o3, h1, h2, h3, h4, bits, i=0, enc='';

	do { // pack three octets into four hexets
		o1 = data.charCodeAt(i++);
		o2 = data.charCodeAt(i++);
		o3 = data.charCodeAt(i++);

		bits = o1<<16 | o2<<8 | o3;

		h1 = bits>>18 & 0x3f;
		h2 = bits>>12 & 0x3f;
		h3 = bits>>6 & 0x3f;
		h4 = bits & 0x3f;

		// use hexets to index into b64, and append result to encoded string
		enc += b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
	} while (i < data.length);

	switch( data.length % 3 ){
		case 1:
			enc = enc.slice(0, -2) + '==';
		break;
		case 2:
			enc = enc.slice(0, -1) + '=';
		break;
	}

	return enc;
}

function get_object_vars (obj) {
    // Returns an array of object properties  
    // 
    // version: 1004.2314
    // discuss at: http://phpjs.org/functions/get_object_vars    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: function Myclass () {this.privMethod = function (){}}
    // *     example 1: Myclass.classMethod = function () {}
    // *     example 1: Myclass.prototype.myfunc1 = function () {return(true);};
    // *     example 1: Myclass.prototype.myfunc2 = function () {return(true);}    // *     example 1: get_object_vars('MyClass')
    // *     returns 1: {}
    var retArr = {}, prop = '';
 
    for (prop in obj) {        if (typeof obj[prop] !== 'function' && prop !== 'prototype') {
            retArr[prop] = obj[prop];
        }
    }
    for (prop in obj.prototype) {        if (typeof obj.prototype[prop] !== 'function') {
            retArr[prop] = obj.prototype[prop];
        }
    }
        return retArr;
}

function carousel(param){
    var c = this;
    window.carousel_cache = [];
    
    var params ={
            prevButtonId:'', //айдишник кнопки "назад"
            nextButtonId:'', //айдишник кнопки "вперёд"
            url:'', //url, куда пойдём за догрузкой резалтов
            arrowsId: '', //айдишник элемента, в котором содержаться кнопоки
            listId: '', //айдишник элемента, куда будут подгружаться результаты
            lastIdInputId: '', //айдишник элемента, где хранится инфа о последнем айдишнике или оффсете
            
            new_carousel_list_name: '', //переменная, в которой придут новые данные карусели
            new_last_id_name: '', //переменная, в которой придут новые данные по последнему айдишнику или оффсету
            
            list_offset: 0, //оффсет
            show_count: 0, //максимальное количество показываемое на экране
            count: 0 //общее количество
        };
    

    jQuery(document).ready(function() {
        jQuery('#'+params.prevButtonId).click( 
                    function () {
                    	if (params.list_offset > 0) {
                    		c.unlockNext();
                			params.list_offset = params.list_offset - params.show_count > 0 ? params.list_offset - params.show_count : 0;
                			if (params.list_offset <= 0) {
                				c.lockPrev();
                			}
                			jQuery('#'+params.prevButtonId).addClass('arrow_preloader');
                			c.showRange();
                		}
                    	
        });
            jQuery('#'+params.nextButtonId).click( 
                    function () {
                    	if (params.list_offset+params.show_count<params.count)
                		{
                			c.unlockPrev();
                			params.list_offset = params.list_offset + params.show_count;
                			b = params.count-params.list_offset>params.show_count?params.show_count+params.list_offset:params.count;
                			if (b>=params.count)
                			{
                				c.lockNext();
                			}
                			jQuery('#'+params.nextButtonId).addClass('arrow_preloader');
                			c.showRange();
                		}
           });
       });

    this.showRange = function()
    {
    	offset = params.list_offset
    	offset = offset || 0;
    	if(typeof(window.carousel_cache[offset]) == 'undefined')
    	{
    	    jQuery.ajax({
    	        type: "POST",
    	        data:
    		    { 
    	    	    last_id: jQuery('#'+params.lastIdInputId).attr('value')
    	        },
    	        url: params.url,
    	        success: function (response_json) {
    	        	  var response = eval( "(" + response_json + ")" );
    	        	  window.carousel_cache[offset] = response[params.new_carousel_list_name]; 
    	        	  jQuery('#'+params.arrowsId+' a.arrow_preloader').removeClass('arrow_preloader');
    	        	  jQuery('#'+params.listId).html(response[params.new_carousel_list_name]);
    	        	  jQuery('#'+params.lastIdInputId).attr('value', response[params.new_last_id_name])
    	        }
    	    });
    	}
    	else
    	{
    		jQuery('#'+params.arrowsId+' a.arrow_preloader').removeClass('arrow_preloader');
            jQuery('#'+params.listId).html(window.carousel_cache[offset]);
    	}
    }
    
    this.lockPrev = function()
    {
        jQuery('#'+params.prevButtonId).removeClass('prev').addClass('prev-disabled').attr('disabled','true');
    }
    
    this.unlockPrev = function()
    {
        jQuery('#'+params.prevButtonId).removeClass('prev-disabled').addClass('prev').removeAttr('disabled');
    }
    
    this.lockNext = function()
    {
    	jQuery('#'+params.nextButtonId).removeClass('next').addClass('next-disabled').attr('disabled','true');
    }

    this.unlockNext = function()
    {
    	jQuery('#'+params.nextButtonId).removeClass('next-disabled').addClass('next').removeAttr('disabled');
    }
    
    // установить новые параметры
    this.setParam = function(param)
    {
        params = c.array_merge(params,param);
        window.carousel_cache[0] = jQuery('#'+params.listId).html();
    };
    
    // склеить параметры
	this.array_merge = function()
	{    
	     var res = {};
	     for (var i = 0; i < arguments.length; i++)
	         for (id in arguments[i]) 
	        	 if (typeof(arguments[i][id])=='object') 
	        		 res[id]=array_merge(res[id], arguments[i][id]); 
	        	 else 
	        		 res[id]=arguments[i][id];
	     return res;
	 };
    
    /* init class */
    c.setParam(param);
}