// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
ulepszacz={
  config:{
    animation_time:700,
    short_animation_time:50,
    timeout:3000,
    autosuggest_timeout:1500,
    ids:{
      flash:{
        flash_error: "#flashError",
        flash_notice: "#flashNotice"
      },
      comment:{
        textarea: "#comment_body",
        submit: "#comment_submit",
        form: "new_comment",
        div: "commentsList",
        discussion_empty: "discussionEmpty"
      },
      loading:"loading",
      howtobox:"howToBox",
      map:{
        checkbox: 'idea_show_map',
        div: "new_idea_gmap",
        div_show: "idea_map",
        submit: "map_address_submit",
        input: 'map_address',
        longitude: 'idea_longitude',
        latitude: 'idea_latitude',
        zoom: 'idea_zoom'
      },
      idea:{
        submit:'idea_submit',
        form: 'new_idea',
        title: 'idea_title',
        similarDiv: 'similarIdeas',
        invites: 'inviteFriends',
        invitesImg: 'inviteFriendsImg'
      }
    },
    classes:{
      idea:{
        votebox: "votebox"
      }
    },
    preloaded_images:['layout/grey/vote_up_hover.png', 'layout/grey/vote_down_hover.png', 'layout/grey/menu_item_hover.png'],
    images_rel_path:"/images/"
  },
  map:{
    center:{},
    draw:{},
    gmap:{}
  },
  set_authenticity_token:function(){
    $(document).ajaxSend(function(event, request, settings) {
      if (typeof(AUTH_TOKEN) == "undefined") {return;}
      // settings.data is a serialized string like "foo=bar&baz=boink" (or null)
      settings.data = settings.data || "";
      settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
    });
  },
  animate_flash_messages:function(){
    var divs_array = [ulepszacz.config.ids.flash.flash_notice, this.config.ids.flash.flash_error].join(',');
    var divs = $(divs_array);
    divs.hide();
    divs.show(ulepszacz.config.animation_time);
    // divs.show('slow');
  },
  create_loading_div:function(){
    $("body").append('<div id="'+ulepszacz.config.ids.loading+'"><img src="/images/ajaxloader.gif" alt="loading" />ładuję...</div>');
  },
  show_loading_div:function(){
    $("#" + ulepszacz.config.ids.loading).show();
  },
  hide_loading_div:function(){
    $("#" + ulepszacz.config.ids.loading).hide();
  },
  // bind_add_comment:function(){
  //   $(ulepszacz.config.ids.comment.submit).click(function(e){
  //     e.preventDefault();
  //     if($(ulepszacz.config.ids.comment.textarea).val().length === 0){
  //       alert('Musisz wpisać treść komentarza');
  //     }else{
  //       var form = $("#"+ulepszacz.config.ids.comment.form);
  //       var textarea = $(ulepszacz.config.ids.comment.textarea);
  //       var value = textarea.val();
  //       var idea_id = $("#comment_idea_id").val();
  //       var comments_div = $("#"+ulepszacz.config.ids.comment.div);
  //       var discussion_empty = $("#"+ulepszacz.config.ids.comment.discussion_empty);
  //       ulepszacz.show_loading_div();
  //       $.post(form.attr('action'), { "comment[value]": value, "comment[idea_id]": idea_id },
  //       function(data){
  //         comments_div.append(data);
  //         discussion_empty.hide();
  //         textarea.attr('value', '');
  //          // $("#commentList div.comment:last-child").hide().slideDown('slow').effect('highlight', {}, 5000);
  //          // // $.scrollTo( $("#commentList div.comment:last-child"), 1500 );
  //          // $("#comment_value").attr('value', '');
  //          // $("#comment_submit").attr("disabled", false);
  //          ulepszacz.hide_loading_div();
  // 
  //      });
  //     }
  //   });
  // },
  bind_ajax_ideas_voting:function(){
    $("." + ulepszacz.config.classes.idea.votebox + " a").click(function(e){
      e.preventDefault();
      var klasa = $(this).parent().attr('class');
      var anchor = $(this);
      var votebox = anchor.parent().parent();
      var url = this.href;
      ulepszacz.show_loading_div();
      $.ajax({
        type: "POST",
        data: {_method: "post"},
        url: url,
        cache: false,
        success: function(xml){
          if(klasa == 'voteup'){
            votebox.find('.voteup').hide();
            votebox.find('.votedown').hide();
            anchor.parent().parent().find('.invitebox').show();
          }else{
            anchor.parent().siblings('.voteup').addClass('voted').children('a').hide().after('<span>za</span>');
            anchor.hide().after('<span>przeciw</span>');
          }
          anchor.parent().siblings('.votes').children('span').hide().html($(xml).find('rank').text()).slideDown(ulepszacz.config.animation_time);
          ulepszacz.hide_loading_div();
        }
      });
    });
  },
  bind_invite_friends:function() {
    $('.invitebox a').live('click', function(e) {
      e.preventDefault();
      ulepszacz.show_invite_modal(this.href);
    });
  },
  show_invite_modal:function(url){
    $('body').append('<div id="modal" /><a href="' + url + '" id="modalTrigger" />');
    $('#modal').jqm({modal: true, ajax: '@href', trigger: $("#modalTrigger")});
    $("#modalTrigger").click();
    ulepszacz.hide_loading_div();
  },
  hide_invite_modal:function() {
    $('#modal').remove();
    $('#modalTrigger').remove();
    $('.jqmOverlay').remove();
  },
  bind_hide_modal:function() {
    $('.modalClose').live('click', function(e) {
      e.preventDefault();
      ulepszacz.hide_invite_modal();
    });
  },
  bind_lightbox:function(){
    $('a.attachment').lightBox({fixedNavigation:true});
  },
  preload_images:function(){
    jQuery.each(ulepszacz.config.preloaded_images, function(){
      jQuery("<img>").attr('src', ulepszacz.config.images_rel_path + this);
    });
  },
  howtobox_hover:function(){
    $('#'+ulepszacz.config.ids.howtobox+' img').imghover();
  },
  new_idea_gmap:function(){
    var point = new GLatLng(ulepszacz.map.center.latitude, ulepszacz.map.center.longitude);
    var map = new google.maps.Map2(document.getElementById(ulepszacz.config.ids.map.div));
    var marker = new GMarker(point, {draggable: true});
    var latitude_input = $("#"+ulepszacz.config.ids.map.latitude);
    var longitude_input = $("#"+ulepszacz.config.ids.map.longitude);
    var checkbox = $("#"+ulepszacz.config.ids.map.checkbox);
    var div = $("#"+ulepszacz.config.ids.map.div);
    ulepszacz.map.gmap = map;
    
    
    ulepszacz.map.gmap.setCenter((point), 13);
    ulepszacz.map.gmap.enableContinuousZoom();
    ulepszacz.map.gmap.addControl(new GLargeMapControl());
    ulepszacz.map.gmap.addControl(new GMapTypeControl());
    ulepszacz.map.gmap.addOverlay(marker);
    marker.enableDragging();
    
    GEvent.addListener(marker, "dragend", function(latlng) {
      var lat = latlng.lat();
      var lng = latlng.lng();
      latitude_input.val(lat);
      longitude_input.val(lng);
    });
    
    if(!checkbox.attr("checked")){
      div.hide();
    }
    
    $(checkbox).click(function(){
      if(checkbox.attr("checked")){
        div.slideDown(ulepszacz.config.animation_time, function(){
          map.checkResize();
          longitude_input.val(marker.getLatLng().lng());
          latitude_input.val(marker.getLatLng().lat());
        });
      }else{
        div.slideUp(ulepszacz.config.animation_time, function(){
          map.checkResize();
          latitude_input.val('');
          longitude_input.val('');
        });
      }
    });
  },
  show_idea_gmap:function(){
    var point = new GLatLng(ulepszacz.map.center.latitude, ulepszacz.map.center.longitude);
    var map = new google.maps.Map2(document.getElementById(ulepszacz.config.ids.map.div_show));
    var marker = new GMarker(point);
    var zoom = ulepszacz.map.center.zoom;
    ulepszacz.map.gmap = map;
    ulepszacz.map.gmap.setCenter((point), zoom);
    ulepszacz.map.gmap.enableContinuousZoom();
    ulepszacz.map.gmap.addControl(new GLargeMapControl());
    ulepszacz.map.gmap.addControl(new GMapTypeControl());
    ulepszacz.map.gmap.addOverlay(marker);
    
    
    
  },
  bind_idea_submit:function(){
    var form = $("#"+ulepszacz.config.ids.idea.form);
    var zoom_input = $("#"+ulepszacz.config.ids.map.zoom);
    var maptype = ulepszacz.map.gmap.getCurrentMapType();
    
    form.submit(function(e){
      zoom_input.val(ulepszacz.map.gmap.getZoom());
      return true;
    });
  },
  edit_idea_gmap:function(){
    this.new_idea_gmap();
    this.bind_idea_submit();
  },
  bind_autosuggest:function(){
    var timeout = ulepszacz.config.autosuggest_timeout;
  	var text = null;
  	var input = $("#"+ulepszacz.config.ids.idea.title);
  	var similarDiv = $("#"+ulepszacz.config.ids.idea.similarDiv);
    similarDiv.hide();
  	input.keyup( function() {
  		if (timeout) clearTimeout(timeout);
  		timeout = setTimeout(function(){ulepszacz.autosuggest_show();}, 1000);
  	});
  	
  },
  autosuggest_show:function(){
    var input = $("#"+ulepszacz.config.ids.idea.title);
    var similarDiv = $("#"+ulepszacz.config.ids.idea.similarDiv);
  	var text = null;
		$.ajax({
			type: "POST",
			url: "/" + ulepszacz.current_site + "/search.xml",
			// data: "search_query=" + $("#newIdeaTitle").val();
      data: "search_query=" + input.val() + "",
			success: function(xml){
				text = '';
				$(xml).find('idea').each(function(){
					_id = $(this).find('id').text();
					_title = $(this).find('title').text();
					_description = $(this).find('description').text();
					_url = $(this).find('url').text();
					_trzykropek = ''
					if (_description.length > 300) {
						_trzykropek = '...'
					}
					text += '<div><a href="' + _url + '" class="similarIdeaLink">' + _title + '</a><div id="similar-idea-"' + _id + '" class=" small similarIdeaDescription quiet">' + _description.substr(0, 300) + _trzykropek + '<a href="' + _url + '" style="display: block;">obejrzyj cały pomysł</a></div></div>';
				});
				text = "<h3>podobne pomysły</h3>" + text;
				similarDiv.html(text);
				$('.similarIdeaLink').each(function(){
					$(this).next().hide();
					$(this).click(function(event){
						event.preventDefault();
						$(this).next().slideToggle("slow");
						//              return false;
					});
				});
				similarDiv.fadeIn(ulepszacz.config.animation_time);
			},
			error: function(){
				similarDiv.fadeOut(ulepszacz.config.animation_time);
			}
		});
  },
  hide_invites_on_idea_show:function(){
    var inviteFriendsDiv = $("#" +ulepszacz.config.ids.idea.invites);
    var a = $("#"+ ulepszacz.config.ids.idea.invitesImg);
    inviteFriendsDiv.hide();
    a.click(function(e){
      e.preventDefault();
      a.slideToggle(ulepszacz.config.animation_time);
      inviteFriendsDiv.slideToggle(ulepszacz.config.animation_time);
    });
  },
  bind_ajax_links:function(){
    $('.votebox a.post').removeAttr('onclick').attr("rel", "nofollow");
  },
  bind_ajax_forms:function() {
    $('form.modalAjax').live('submit', function() {
      $(this).ajaxSubmit({
        target: "#modal"
      });
      return false;
    });
  },
  init:function(){
    this.set_authenticity_token();
    this.bind_ajax_links();
    this.animate_flash_messages();
    this.bind_lightbox();
    this.preload_images();
    this.create_loading_div();
    this.bind_autosuggest();
    this.bind_invite_friends();
    this.bind_hide_modal();
    this.bind_ajax_forms();
    // this.howtobox_hover();
    if(ulepszacz.config.logged){
      // this.bind_add_comment();
      this.bind_ajax_ideas_voting();
    }
    if(ulepszacz.map.draw.new_map){
      this.new_idea_gmap();
      this.bind_idea_submit();
    }
    if(ulepszacz.map.draw.edit_map){
      this.edit_idea_gmap();
    }
    
    if(ulepszacz.map.draw.existing){
      this.show_idea_gmap();
    }
    
    if(ulepszacz.config.hide_invites){
      this.hide_invites_on_idea_show();
    }
  }
};

$(document).ready(function(){
  ulepszacz.init();
});