function check_search_submit(o) {
	var query = $(o).find("input[name=query]").attr("value");
	
	if (query.toLowerCase() == "поиск") {
		$(o).find("input[name=query]").attr("value","");
	}
	
}

function showCurrentSlogan() {
  var panel_id = $("#top_slide .panel:first-child").attr('panel_id');
  $("#coda-slogan-1-" + panel_id).fadeIn('fast');
  $("#coda-nav-1 .tab"+panel_id+" a").addClass("current");
}

function hideAllSlogans() {
  $(".slogan").fadeOut("fast");
}

function resizeEmbed(objects, width, height) {	
	for (var i=0; i<objects.length; i++) {
		var obj = objects[i];
		
		var code = obj['video']['code'];
		var source_width_blocks = code.match(/width=\"?(\d+)\"?/gi);
		var source_height_blocks = code.match(/height=\"?(\d+)\"?/gi);
		
		if (source_width_blocks.length != source_height_blocks.length) {
			continue;
		}
		
		for (var j=0; j < source_width_blocks.length; j++) {
			var source_width = source_width_blocks[j].match(/\d+/);
			var source_height = source_height_blocks[j].match(/\d+/);
			
			if (source_width.length == 0 || source_height.length == 0)  {
				continue;
			}
			
			if (parseInt(source_width) == width) {
				continue;
			}
			
			if (height == null || height == undefined) {
				height = Math.floor(width * parseInt(source_height[0]) / parseFloat(source_width[0]));
			}
			
			obj['video']['code'] = obj['video']['code'].replace(source_width_blocks[j], 'width="' + width + '"');
			obj['video']['code'] = obj['video']['code'].replace(source_height_blocks[j], 'height="' + height + '"');
		}
	}
	
	return objects
	
}

function insertVideo(o) {
  if ($(o).parents(".video_thumb_container").hasClass("current")) return false;
  
  var index = parseInt($(o).attr("kasta:index"));
  var type = $(o).attr("kasta:type");
    
  var title = "";
  var code = "";
  var description = "";
  var release = null;
  var credits = "";
  var download_link_url = ""; 
    
  if (type == "video") {
    title = videos[index]["video"]["title"];
    code = videos[index]["video"]["code"];
    description = videos[index]["video"]["description"];
    credits = videos[index]["video"]["credits"];
    download_link_url = videos[index]["video"]["item_url"];
    
    if (videos[index]["video"].hasOwnProperty("release")) {
      release = videos[index]["video"]["release"];
    }
  } else if (type == "live_video") {
    title = live_videos[index]["video"]["title"];
    code = live_videos[index]["video"]["code"];
    description = live_videos[index]["video"]["description"];
    credits = live_videos[index]["video"]["credits"];
    download_link_url = live_videos[index]["video"]["item_url"];

    if (live_videos[index]["video"].hasOwnProperty("release")) {
      release = live_videos[index]["video"]["release"];
    }
  } else if (type == "clip_video") {
    title = clip_videos[index]["video"]["title"];
    code = clip_videos[index]["video"]["code"]
    description = clip_videos[index]["video"]["description"];
    credits = clip_videos[index]["video"]["credits"];
    download_link_url = clip_videos[index]["video"]["item_url"];
    
    if (clip_videos[index]["video"].hasOwnProperty("release")) {
      release = clip_videos[index]["video"]["release"];
    }
  }
    
  $("#player1").html(code);
  
  // Inserting video details if there is a place we could insert to
  $("div.about_clip").children("h1").html(title);
  if (release != null && release != undefined) {
    $("div.about_clip").find("a").attr("href", "/releases/" + release["id"]).html(release["title"]);
    $("div.about_clip").find("span.release_year").html(release["released_at"].split("-")[0]);
  }
  
  if (credits != "" && credits != null) {
    $("div.about_clip").find("span.credits").text(" | " + credits.replace(/(<([^>]+)>)/ig,""));
  } else {
    $("div.about_clip").find("span.credits").html("");
  }
  
  if (description != "" && description != null && description != undefined) {
    $("div.clip_description").show().children(".about_me").html(description);
  } else {
    $("div.clip_description").children(".about_me").html("");
    $("div.clip_description").hide();
  }
  
  if (download_link_url != "" && download_link_url != null && download_link_url != undefined && download_link_url != "/images/empty.gif") {
    $("p.download_video").html("<a href='" + download_link_url + "'>скачать</a>");
  } else {
    $("p.download_video").html("");
  }
        
  $(o).parents(".videos_container").find(".video_thumb_container.current").removeClass("current");
  $(o).parents(".video_thumb_container").addClass("current"); 
  
  return false;
}



function selectDownloadCategory(args) {
  var category_name = args.selectedVal;
  
  if (category_name == "_all_") {
    $(".download_category").show();
  } else {
    $(".download_category[rel!=" + category_name + "]").hide();
    $(".download_category[rel=" + category_name + "]").show();
  }
}

function selectPoll(args, init) {
  var poll_id = args.selectedVal;
  
  if (poll_id == "_all_") {
    var re = /poll_(\d+)/;
    if (re.test(location.href)) {
      poll_id = re.exec(location.href)[1];
    } else {
      poll_id = window.last_poll_id;
    }
  }
  $(".poll_data").hide();
  $(".poll_data_"+poll_id).show();
  if (location.hash.indexOf("#") != -1) {
    location.hash = "#poll_"+poll_id;
  }

	if (!init) {
		$.scrollTo("div.opros");
  }
}

function selectMobileCountry(args) {
  var country_index = args.selectedVal;
  
  $(".mobile_choice_tabs[rel!=" + country_index +"]").hide();
  $(".mobile_choice_tabs[rel=" + country_index + "]").show();
}

$(function(){
  hideAllSlogans();
  showCurrentSlogan();
  var scroll1 = new scroller("#top_slide", {data_selector : "li.panel", visible_children : 2, content_width : 727, duration : 0.1, loop : true, steps : ($.browser.msie ? 15 : 50), auto_slide : 12});
  
  $("#top_slide").bind('scroller.start', function(event, direction) {
    hideAllSlogans();
    $("#coda-nav-1 a.current").removeClass("current");
  }).bind('scroller.stop', function(event, direction) {
    showCurrentSlogan();
  }).mouseenter(function(event) {
    scroll1.pause_auto_slide();
  }).mouseleave(function(event) {
    scroll1.resume_auto_slide();
  });
  
	$("#coda-nav-1").mouseenter(function(event) {
		scroll1.pause_auto_slide();
	}).mouseleave(function(event) {
		scroll1.resume_auto_slide();
	});

  $("#coda-nav-1 a").mouseover(function() {
		scroll1.pause_auto_slide();
    
		var target = parseInt($(this).attr('rel').substring(1));
    var current = parseInt($("#top_slide .panel:first").attr('panel_id'));
    try {
      var count = Math.abs(target - current);
      var left = current > target;
      var i;
			var duration = null;
			var steps = null;
			if (count > 1) {
				duration = 0.01;
				steps = ($.browser.msie ? 4 : 10);
			}
			
      for(i = 0; i < count; i++) {
				scroll1.schedule_scroll(left, duration, steps);
      }
    }
    catch(e) {
      alert(e);
    }
    return false;
  });
  
  
  $("#video_tabs").tabs();
  $("#mobile_tabs").tabs();
  
  if (!!($(".tab_button.selected")).get(0)) {
    var selected_tab = parseInt($(".tab_button.selected").attr("href").match("[0-9]+$")[0]) - 1;
  } else {
    var selected_tab = 0;
  } 
  $(".mobile_choice_tabs").tabs({ selected: selected_tab });
  
  var scroll2 = new scroller("#video_tab-1", {data_selector : "li.panel", visible_children : 5, content_width : 76, duration : 0.2, loop : true, steps : 15});
  var scroll3 = new scroller("#video_tab-2", {data_selector : "li.panel", visible_children : 5, content_width : 76, duration : 0.2, loop : true, steps : 15});
  var scroll4 = new scroller("#video_tab-3", {data_selector : "li.panel", visible_children : 5, content_width : 76, duration : 0.2, loop : true, steps : 15});
  
  var scrollBiography = new scroller(".biografy_year", {data_selector : "li.biografy_icon", visible_children : 6, content_width : 160, duration : 0.2, loop : false, steps : 15});

  $("a.video_thumb_link").live("click", function() {
    return insertVideo(this);
  });
  
  $('#video_tabs a.video_thumb_link').tooltip({ 
      track: true, 
      delay: 0, 
      showURL: false, 
      fade: 250 
  });
  
  if (!!($(".hot_news").get(0))) {
    $(".news_expand").live('click', function() {
      $(this).parents("table").next().slideDown('slow');
      $(this).removeClass("news_expand").addClass("news_collapse");
      $(this).prev().css({color: "#FFFFFF"})
    });

    $(".news_collapse").live('click', function(){
      $(this).parents("table").next().slideUp('slow');
      $(this).removeClass("news_collapse").addClass("news_expand");
      $(this).prev().css({color: "#50ADBE"});
    });

    $(".open_all_hot_news").click(function() {
      $(".news_preface").slideDown("slow");
      $(".news_expand").removeClass("news_expand").addClass("news_collapse");
      $(".news_title").css({color: "#FFFFFF"});

      return false;
    });
  }
    
  $("a.show_more").live("click", function() {
    var $truncated_description = $("div.about_me > span.truncated_description");
    
    if ($truncated_description.css("display") == "none") { 
      $truncated_description.show();
    } else {
      $truncated_description.hide();
    }
    
    $(this).hide(); // I hide it and show then to prevent moving this element in the block
    
    $img = $(this).children("img");
    if ($img.hasClass("expand")) {
      $img.addClass("collapse").removeClass("expand").attr("src", "/images/icons/str7_upper.gif");
    } else {
      $img.addClass("expand").removeClass("collapse").attr("src", "/images/icons/str7.gif");
    }
    
    var $all_description = $("span.all_description");
    
    if ($all_description.css("display") == "none") { 
      $all_description.show();
    } else {
      $all_description.hide();
    }
    
    $(this).show();
    
    return false;
  });
  
  $(".tracks_container").find(".accordion").live("click", function() {
    var $more = $(this).parent().find(".more_info");
    
    var close = $more.hasClass("current");
    if (close) {
      $(this).parents(".tracks_container").find(".more_info.current").removeClass("current").hide();
    } else {
      $(this).parents(".tracks_container").find(".more_info.current").removeClass("current").hide();
      $more.show().addClass("current");
    }
    
    return false;
  });
  
  $("a[rel='photoalbum']").colorbox();
  
  $("#download_categories").selectbox({
      onChangeCallback: selectDownloadCategory,
      inputType: 'span',
      useInputWrapper: true,
      inputWrapperTag: 'a',
      inputWrapperClass: '',
			useContainerWrpapper: true,
			containerWrapperClass: 'selectfix'
    });

  $("#poll_selection").selectbox({
      onChangeCallback: selectPoll,
      inputType: 'span',
      useInputWrapper: true,
      inputWrapperTag: 'a',
      inputWrapperClass: '',
			useContainerWrpapper: true,
			containerWrapperClass: 'selectfix'			
    });
    
  $("#mobile_countries").selectbox({
      onChangeCallback: selectMobileCountry,
      inputType: 'span',
      useInputWrapper: true,
      inputWrapperTag: 'a',
      inputWrapperClass: '',
			useContainerWrpapper: true,
			containerWrapperClass: 'selectfix'
  });
  
  // /artists selection
  $('.biografy_more').anchorNav({
    nav: ".anchor-nav",
		preventScrollToAnchor: true,
    updateNavFn: function(name) {
      $(".biografy_year_ins li").removeClass('select');
      $(".biografy_year_ins li > a[href=#" + name + "]").parent().addClass('select');
    },
    currentNavFn: function() {
      $(".biografy_year_ins li").removeClass('select');
      name = $(this).attr("href").split('#')[1];
      $(".biografy_year_ins li > a[href=#" + name + "]").parent().addClass('select');
    },
    noAnchorFn: function() { 
      $('.biografy_more').children().hide().eq(0).show(); 
      $(".biografy_year_ins li").eq(0).addClass('select');
    },
    showFn: function() { $(this).fadeIn(); }
  });
  
  // For search field
  var default_text = "Поиск";
  $("#search").find("input[name=query]").focus(function() {
    // Clear text
    if (this.value == default_text) {
      this.value = "";
    }
  });
  
  $("#search").find("input[name=query]").blur(function() {
    if (this.value == "") {
      this.value = default_text;
    }
  });
});


