var SnowDB = {};

function showShopMap(x,y,zoom,text) {
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("shop-map-div"));
		map.setCenter(new GLatLng(x,y), zoom);
		map.addControl(new GSmallMapControl());

		var marker = new GMarker(new GLatLng(x,y));
		map.addOverlay(marker);
		map.openInfoWindow(map.getCenter(),document.createTextNode(text));
	}
}


function try_hide_field_block(){
    var elements_exist = false;
    var elements = $$('#hidden_fields_box UL LI');
    for(var el in elements){
       if(typeof(elements[el]) == 'function')continue ;
       if(elements[el].style['display'] != 'none'){
           elements_exist = true;
           var d = elements[el].innerHTML;
       }
    }
    if(elements_exist)
	    new Effect.Appear('hidden_fields_box', {duration:1});
    else
	    new Effect.Fade('hidden_fields_box', {duration:1});
}

function field_toggle(visible,field_id){
	new Ajax.Request("/snowboard/toggle_field/" + field_id, {
	  method: 'get',
	  onSuccess: field_toggled
	});
}

function field_toggled(resp){
	var obj = resp.responseText.evalJSON();
	
	row_id = 'field_row_' + obj.id;
	show_link_id = 'show_field_' + obj.id;
	params = {duration:1, afterFinish:try_hide_field_block};
	
	if(obj.visible){
		new Effect.Appear(row_id, params);
		new Effect.DropOut(show_link_id, params);
	} else {
		new Effect.Fade(row_id, params);
		new Effect.Appear(show_link_id, params);
	}
}

function l(key){
  return SnowDB.app.getLog(key);
}

function main_on_load(){
  SnowDB.app = new SnowDB.App();
  
Ajax.Responders.register({
  onCreate: SnowDB.app.beginRequest.bind(SnowDB.app), 
  onComplete: SnowDB.app.endRequest.bind(SnowDB.app)
});
}

function getNewId() {
  window.lastGenId++;
  return "window_id_" + window.lastGenId;
}

function l(key){
  return SnowDB.app.getLoc.call(SnowDB.app,key);
}

function set_cookie( name, value, expires, path, domain, secure ) 
{
var today = new Date();
today.setTime( today.getTime() );
if ( expires ){expires = expires * 1000 * 60 * 60 * 24;}
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 get_cookie( check_name ) {
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false;
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		a_temp_cookie = a_all_cookies[i].split( '=' );
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			if ( a_temp_cookie.length > 1 )
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found ) return null;
}	
	
function delete_cookie( name, path, domain ) {
if ( Get_Cookie( name ) ) document.cookie = name + "=" +
( ( path ) ? ";path=" + path : "") +
( ( domain ) ? ";domain=" + domain : "" ) +
";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function installSearchPlugin(lang) {
	var url = "/search_addon/snowdb_" + lang + ".xml";
	try {
		window.external.AddSearchProvider(url);
	} catch (e) {
		alert("You need to be using IE7 or Firefox2 to add a search engine\r\nYou can also install search plugins by using the drop down menu to the right of the search box.");
		return;
	}
}

	SnowDB.App = Class.create({
    
    initialize : function(){
        this.init_tooltips();
    },
    
    init_tooltips : function(){
        $$('.tt_elm').each(function(e){
            var tte = $(e.id + '_tt');
            if(tte){
                new Tip(e.id,tte.innerHTML);
                //new Tooltip(e.id, tte.id);
            }
        });
    },
    
    localization: {
      en : {
          cmp_in_list : 'In list!',
          search_clause : 'search',
          signup_win_title : 'Signup',
          code_copied : 'The code is in your clipboard now!'
      },
      ru : {
          cmp_in_list : 'В списке!',
          search_clause : 'поиск по сайту',
          signup_win_title : 'Регистрация',
          code_copied : 'Код скопирован в ваш буфер обмена!'
      }
    },
    
    updateBlogMod : function(){
        var id = $('mod_picker').value;
        $('blog_loading').appear({ duration: 0.35 });
        new Ajax.Request("/snowboard/blog/" + id, {
	  method: 'get',
	  onSuccess: this.updateBlogCode.bind(this)
	});
    },
    
    updateBlogCode : function(resp){
        $('blog_loading').fade({ duration: 0.35 });
        var obj = resp.responseText.evalJSON();
        $('blog_full_ta').value = obj.full;
        $('blog_mini_ta').value = obj.mini;
        $('blog_full_div').update(obj.full_local);
        $('blog_mini_div').update(obj.mini_local);
    },
    
    getLoc : function(key){
      if(! this.lang){this.lang = SnowDB.App.lang;}
      return this.localization[this.lang][key];
    },

    show_signup_win : function(){
      this.current_win = new SnowDB.SignupWin();
      this.current_win.show();
    },
    
    copy_blog_code : function(ta){
      ta.focus();
      ta.select();
    },
    
    beginRequest : function(){
    	if(this.current_win && typeof(this.current_win.shade) == 'function') 
                  this.current_win.shade();
    },

    endRequest : function(){
    	if(this.current_win && typeof(this.current_win.unshade) == 'function')
    		this.current_win.unshade();
    },
    
    brand_selector_focus : function(){
        this.show_brand_selector();
    },

    show_brand_selector : function(){
        $('brand_selector').appear({duration: 0.5});
        $('asf_show_brand_selector').hide();
        $('asf_hide_brand_selector').show();
        this.brand_selector_visible = true;
    },

    close_brand_selector : function(){
        $('brand_selector').fade({duration: 0.5});
        $('asf_hide_brand_selector').hide();
        $('asf_show_brand_selector').show();
        this.brand_selector_visible = false;
    },

    toggle_brand_selector : function(){
        if(this.brand_selector_visible)
          this.close_brand_selector();
        else{
          this.show_brand_selector();
          $('asf_brand_fld').focus();
        }
          
    },

    brand_selector_blur : function(){
        this.close_brand_selector_by_timeout(200);
    },

    close_brand_selector_by_timeout : function(delay){
      this.closeBrandSelectorTimeout = setTimeout(this.close_brand_selector.bind(this),delay);  
    },
    
    
    brand_selector_checked : function(){
        if(this.closeBrandSelectorTimeout) clearTimeout(this.closeBrandSelectorTimeout);
        
        var new_value = '';
        for(var i=0;i<brands.length;i++){
            var brand = brands[i];
            if($('asf_brand_' + brand['id']).checked){
                if(new_value != '') new_value += ', ';
                new_value += brand['name'];
            }
        }
        $('asf_brand_fld').setValue(new_value);
        $('asf_brand_fld').focus();
    },

    added_to_comparison : function(resp){
    	var id = resp.responseText.evalJSON();
        $('adding_to_cmp_' + id).hide();
        if(id == false){
            $('btn_add_to_cmp_' + id).show();
        } else {
            $('add_to_cmp_cell_' + id).update("<a href='/comparison/show/current'>" + this.getLoc('cmp_in_list') + "</a>");
        }
    },

    add_to_comparison : function(id){
        $('btn_add_to_cmp_' + id).hide();
        $('adding_to_cmp_' + id).show();
        new Ajax.Request("/comparison/add/" + id, {
          method: 'get',
          onSuccess: this.added_to_comparison.bind(this)
        });
        return false;
    }
});