document.observe("dom:loaded", function() {
    if ($("loading_container")) {
        resize_view_item_image();
    }

    if  ($("login")) {
        $("login").focus();
    } else if($("login_admin")){
        $("login_admin").focus();
    } else if($("search_query")){
        $("search_query").focus();
    }

    modal_windows();

    $$("div.faq_answer").each(function(e) {
        e.style.display = "none";
    });

    // In case where no submit button is present on a form, "Enter" will not
    // execute form submittion. Add submit event on "Enter".
    $$("input").invoke("observe", "keydown", function(event) {
        if (event.keyCode == 13) {
            if (this.form) {
                validate_and_submit(this.form);
                this.blur();
            }
        }
    });
		
});

// Submit form. If validations exist, check to make sure they all pass before submitting.
function validate_and_submit(form) {
    //try {
        if (LiveValidation.massValidate(LiveValidationForm.getInstance(form).fields)) {
            form.submit();
        }
    //} catch(e) {}
}

function clean_output(initial_field, target_field){
    $(target_field).value = $(initial_field).value.gsub(/%|\|'|"|\/|\?/, '')
}

function modal_windows() {
    $$(".create_modal_window").each(function(link) {
        create_modal_window(link);
    });
}

function create_modal_window(link) {
    var indicator = false;
    if (!link.id.blank() && link.id.strip().startsWith("id:")) {
        indicator = "indicator:" + link.id.strip().sub("id:", "");
    }
    var modal = new Control.Modal(link,{
        className: 'modal_window',
        indicator: indicator
    });
}

function resize_view_item_image() {
    var img = $("view_item_image");
    if (img) {
    /*
        var max_height = 200;
        var max_width = 400;
        var height_multiplier = img.height / max_height;
        var width_multiplier = img.width / max_width;
        var largest_multiplier = Math.max(height_multiplier, width_multiplier);
        if (largest_multiplier > 1) {
            img.name = largest_multiplier;
            img.height /= largest_multiplier;
            if (!document.all) {
                img.onmouseover = function() {
                    this.width *= this.name;
                    this.height *= this.name;
                    this.style.top = Position.cumulativeOffset(this)[1] + "px";
                    this.style.left = Position.cumulativeOffset(this)[0] + "px";
                    this.style.position = "absolute";
                    this.style.zIndex = 500;
                    this.style.border = "2px solid #039";

                };
                img.onmouseout = function() {
                    this.style.top = "0px";
                    this.style.left = "0px";
                    this.style.position = "relative";
                    this.height /= this.name;
                    this.width /= this.name;
                    this.style.zIndex = 0;
                    this.style.border = "none";
                };
            }
        }
        */
        $("loading_container").hide();
        $("view_item_image_div").style.height="";
        $("view_item_image_div").style.overflow="";
    }
}

function description_full_iframe_update(url) {
    $("description_full_iframe").update('<iframe src="' + url + '", style="border: 1px solid #ccc; width: 930px; height: 500px; margin: 10px;">');
}

function show_modal_window(title, myUrl) {
    win = new Window('window_id', {title: title, width:1000, height:700, url:myUrl});
    win.setDestroyOnClose();
    win.showCenter();
}

function include(file) {
  var script  = document.createElement('script');
  script.src  = file;
  script.type = 'text/javascript';
  script.defer = true;

  document.getElementsByTagName('head').item(0).appendChild(script);
}

include('/javascripts/bayru.js');

var confirm_merge_modal = false;
function create_confirm_merge_modal() {
    if(confirm_merge_modal != false) {
        try {
            confirm_merge_modal.destroy();
        }catch(err){}
        confirm_merge_modal = false;
    }
    confirm_merge_modal = new Control.Modal($('confirm_merge'), {
            className: 'modal_window'
    });

}

function Gallery(content, gallery_prefix_class, args){
  this.get_reference = function(){
      reference_images = [];
      ref = this.reference%this.imagesPerView==0 ? this.reference : (this.reference/this.imagesPerView | 0) * this.imagesPerView;
      for(i=ref, j=0; i<ref+this.imagesPerView; i++, j++ ){
          if(this.content[i]==undefined){break;}
          else{reference_images[j] = this.content[i];}
      }
      return reference_images;
  };
  this.change_reference = function(new_reference){
      this.reference = new_reference;
  };

  this.update_zoom = function(){
      if(typeof(this.zoomClass)!="undefined"){
          victim_index = 0;
          zoom_links = 0;
          old_href =  $$("a."+this.zoomClass)[zoom_links].href;
          new_href = old_href.replace(/count=(\d+)/,"count="+this.reference);
          if(typeof(all_lightboxes) != "undefined"){
            for(victim_index=0; victim_index<all_lightboxes.length; victim_index++){
              if(all_lightboxes[victim_index].content==old_href){
                        $$("a."+this.zoomClass)[zoom_links].href = new_href;
                        all_lightboxes[victim_index].content = new_href;
                        zoom_links++;
              }
            }
          };
        $$("a."+this.zoomClass).each(function(link){
            link.href = new_href;
          }
        )

      }
  };


  this.generate = function(){

      gallery_snippet = this.get_reference();

      i=0;
      for(; i<gallery_snippet.length; i++){
          $$("a."+this.gallery_prefix_class)[i].style.display = "";
          entire_content = gallery_snippet[i].split("||||||");
          if(entire_content[0]!=undefined){
                $$("img." + this.gallery_prefix_class)[i].src = entire_content[0];
          }

          if(entire_content[1]!=undefined){
            $$("span." + this.gallery_prefix_class)[i].innerHTML = entire_content[1];
          }
          if(entire_content[2]!=undefined){
            $$("strong." + this.gallery_prefix_class)[i].innerHTML = entire_content[2];
          }
      }

      while(i<this.imagesPerView){
        try{$$("a."+this.gallery_prefix_class)[i].style.display = "none";}
        catch(e){}
        i++;
      }

  };

  this.increment_reference = function (){
      if((((this.reference + this.imagesPerView)/this.imagesPerView)|0)* this.imagesPerView < this.size()){
        this.reference = this.reference - this.reference % this.imagesPerView + this.imagesPerView;
      }
      this.add_border();
      this.show_information();
  };

  this.show_information = function(){
      if(this.galleryInformationBarId != undefined){
       $(this.galleryInformationBarId).innerHTML = "Фото: " + (this.reference+1) + "/" + this.size();
      }
  };

  this.add_border = function(){
      $$("a."+gallery_prefix_class).each(function(img){img.style.borderColor = ""});

      $$("a."+gallery_prefix_class)[this.reference % this.imagesPerView].style.borderColor = "#5a595a";
  };
  this.decrement_reference = function (){
      if(this.reference-this.imagesPerView>=0){
        this.reference = this.reference - this.reference % this.imagesPerView - this.imagesPerView;
      }
      this.add_border();
      this.show_information();
  };

  this.show_big = function(){

     if(this.primaryImageClass!=undefined){
      this.update_zoom();
      curr_obj = this;
      $$("img." + this.primaryImageClass).each(function(img){img.src = curr_obj.content[curr_obj.reference];});
     }

  };
  this.size = function(){
      return this.content.length;
  };

  this.clicker = function(x,offset){
      this.reference = this.reference - (this.reference % this.imagesPerView) + offset;
      this.generate();
      this.show_big();
      this.add_border();
      this.show_information();
  };

  this.move_left_arrow = function(){
      this.decrement_reference();this.generate();this.show_big();
  };

  this.move_right_arrow = function (){
      this.increment_reference();this.generate();this.show_big();
  };

  this.observe = function(){
      temp_obj = this;
      i=0;
      $$("a." + this.gallery_prefix_class).each(function(link){link.observe("click", temp_obj.clicker.bindAsEventListener(temp_obj,i++));});

      if(this.leftArrowClass!=undefined){
        $$("a." + this.leftArrowClass).each(function(link){link.observe("click", temp_obj.move_left_arrow.bind(temp_obj))});
      }
      if(this.rightArrowClass!=undefined){
        $$("a." + this.rightArrowClass).each(function(link){link.observe("click", temp_obj.move_right_arrow.bind(temp_obj))});
      }

      if(this.zoomClass!=undefined){
        $$("a." + this.zoomClass).each(function(link){link.observe("click", function(){window.scroll(0,0);})});
      }
  };

  Object.extend(this, args);
  this.gallery_prefix_class = gallery_prefix_class;
  this.content = content;
  this.reference = 0;
  this.show_information();
  this.add_border();
  this.observe();
}

function TopGallery(left_control, right_control, items_per_view, total_items, inner_content_id, request_path, loading_indicators, partial, conditions){

    this.onload = function(){
       $(inner_content_id).innerHTML =  $(this.loading_indicators).innerHTML
    };

    this.load_content = function(){
        request_params = {reference: this.reference, items_per_view: this.items_per_view, inner_content_id: this.inner_content_id, partial: this.partial};
        Object.extend(request_params, this.conditions);
        new Ajax.Request(this.request_path, {method: "get", parameters: request_params, onLoading: this.onload()});
    };

    this.shift_left = function(){
        if(this.reference-this.items_per_view>=0){
            this.reference = this.reference - this.items_per_view;
            this.load_content();
        }
    };

    this.shift_right = function(){
        if((this.reference+this.items_per_view) < this.total_items){
            this.reference += this.items_per_view;
            this.load_content();
        }
    };

    this.observe = function(){
        temp_obj = this;
        $$("a." + left_control).each(function(link){link.observe("click", temp_obj.shift_left.bind(temp_obj))});
        $$("a." + right_control).each(function(link){link.observe("click", temp_obj.shift_right.bind(temp_obj))});
    };

    this.left_control = left_control;
    this.right_control = right_control;
    this.items_per_view = items_per_view;
    this.total_items = total_items;
    this.inner_content_id = inner_content_id;
    this.request_path = request_path;
    this.loading_indicators = loading_indicators;
    this.partial = partial;
    this.conditions = conditions
    this.reference = 0;
    this.observe();
    this.load_content();

}

function record_clicks(path){
    $$("a.record_clicks").each(function(link){link.observe("click", function(link, value){
        new Ajax.Request(path,
            {method: "get", parameters:
                {id: value.id.replace(/\D+/,"")}
            });
    }.bindAsEventListener(this, link))});
		
}

function Rotator(params){
  this.switcher = function(index, from_click){
     if(from_click){
          this.goer.stop();
        };

    if(index!=this.current_index){
     new Effect.Pulsate(this.gallery_outer, {pulses: 1, duration: 1.6, from: .1});
      setTimeout(function(){
          $(this.gallery_id).src = '/images/' + this.images[index];
        }.bind(this, index), 800);
      this.current_index = index;
      }
    };

  this.observe = function(){
    primary_object=this;
    i=0;
    $$("."+this.controlls_class).each(function(link){
      link.observe("click", function(link, counter){
          primary_object.switcher(counter, true);
      }.bindAsEventListener(this, i++))
    })
  };

  this.start_rotation = function(){
      this.goer = new PeriodicalExecuter(function(){
        new_index = this.current_index + 1;
        if(this.images.length <= new_index){
          new_index = 0;
        };
        this.switcher(new_index, false);
        this.current_index = new_index;
      }.bind(this), 5);
  }
  
  this.current_index = 0;
  Object.extend(this, params);
  this.observe();
  this.start_rotation();
};

function display_large_images(){
    div_large_image = $('large_image_holder');
   if(div_large_image==undefined){
    div_large_image = document.createElement('div');
    div_large_image.id = 'large_image_holder';
    div_large_image.setStyle({
      position: 'fixed',
      top: 0,
      right: 0,
      height: 100,
      border: "1px solid orange"
    });
    document.body.appendChild(div_large_image);
   }
  $$(".show_large_image").each(function(link){link.observe("click", function(link, value, div){
       if($('large_image_holder').firstChild != null && $('large_image_holder').firstChild.src == value.src){
        $('large_image_holder').update();
       }
       else{
         div_large_image.update("<img src='" + value.src + "'/>"); 
       }
      }.bindAsEventListener(this, link, div_large_image))});

};

function display_currency(currency, clicked_link){
        switch(currency){
					case 'rub': display_value = 'Рубли';break;
					case 'usd': display_value = 'Доллары';break;
				 };
				 if(clicked_link.innerHTML=="<b>" + display_value + "</b>"){
					return false;
				 };
         
         $$(".selected_currency").each(function(link){
          link.innerHTML = link.innerHTML.replace(/<\/?[^>]+(>|$)/g, "");
         });

         clicked_link.innerHTML = "<b>" + display_value + "</b>";

         $$('.prices').invoke('hide');
         $$('.prices_' + currency).invoke('show');
				 display_value = '';
				 
				 if($('currency')!=null){
				 	$('currency').value=currency;
				 };
          switch(currency){
					case 'rub': display_value = 'руб.';break;
					case 'usd': display_value = 'USD';break;
				 };
				 $$('.filter_currency').each(function(cur){cur.innerHTML=display_value});

}
