function user_vote(rate, id) {
    $.get("user_vote.html", { rate: rate, broker: id },
   function(data) {
     load_brokers();
   });
}
function load_page(page) {
    $('#h_page').val(page)
    load_brokers()
}

function load_limit(limit) {
    $('#h_limit').val(limit)
    load_brokers()
}

function load_order(order) {
    $('#h_order').val(order)
    load_brokers()
}

function load_video(url){
    document.getElementById('video_frame').src = "http://www.youtube.com/embed/" + url
}

function load_video_popup(url){
    document.getElementById('video_frame_popup').src = "http://www.youtube.com/embed/" + url;
    var wi2 = parseInt($(".drop2").width()/2);
    $("#video_popup").css("marginLeft", -wi2-200+"px")
    $("#video_popup").fadeIn(300);
}

function load_compare(){
    set_ids();
    var ids = $('#compare_ids').val(),
        rnd = Math.random()

    $("#broker_list").load("/compare.html?ids="+ids+"&rnd="+rnd, function(data){
        $(".comp-table tr:nth-child(even)").addClass("com-td");
        $(".srh-r tr td:last").addClass("nobg");
        $(".srn td:last").addClass("bg-r");
        $('#compare_ids').val("")
    });
}
$(document).ready(function(){

jQuery(".niceCheckLogin").each(
    /* при загрузке страницы нужно проверить какое значение имеет чекбокс и в соответствии с ним выставить вид */
    function() {

         changeCheckStart(jQuery(this));

    });
});
jQuery(".niceCheckLogin").mousedown(function(){

    changeCheckLogin(jQuery(this));
})

function changeCheckLogin(el)
/*
	функция смены вида и значения чекбокса
	el - span контейнер дял обычного чекбокса
	input - чекбокс
*/
{
     var el = el,
          input = el.find("input").eq(0);
   	 if(!input.attr("checked")) {
		el.css("background-position","0 0px");
		input.attr("checked", true)
	} else {
		el.css("background-position","0 -34px");
		input.attr("checked", false)
	}
     return true;
}
function load_brokers(search){
    set_ids();
    page = $('#h_page').val();
    limit = $('#h_limit').val();
    order = $('#h_order').val();
    ids = $('#compare_ids').val();
    rnd = Math.random()
    if (search) {
        query = "broker_list.html?search="+search+"&rnd="+rnd
    } else {
        query = "broker_list.html?page="+page+"&limit="+limit+"&order="+order+"&ids="+ids+"&rnd="+rnd
    }
    $("#broker_list").load(query, function(data){


        $(".show span").toggle (function(){
            $(this).parent(".show").addClass("show2");
            $(this).html("Скрыть");
            $(this).parents(".brocker").addClass("br-show");
            $(this).parents(".brocker").find(".br-dop").slideDown("fast");
            }, function(){
            $(this).parent(".show").removeClass("show2");
            $(this).html("Подробнее");
            $(this).parents(".brocker").removeClass("br-show");
            $(this).parents(".brocker").find(".br-dop").slideUp("fast");

            });
        jQuery(".niceCheck").each(
    /* при загрузке страницы нужно проверить какое значение имеет чекбокс и в соответствии с ним выставить вид */
        function() {

             changeCheckStart(jQuery(this));

        });

        

    });



}

function changeCheckStart(el)
/*
	если установлен атрибут checked, меняем вид чекбокса
*/
{
var el = el,
		input = el.find("input").eq(0);

      if(input.attr("checked")) {

		el.css("background-position","0 0");
		}
     return true;
}


function changeCheck(el, id)
/*
	функция смены вида и значения чекбокса
	el - span контейнер дял обычного чекбокса
	input - чекбокс
*/
{
     var el = el,
          input = el.find("input").eq(0),
          parent = el.parents(".brocker-table").get(0),
          name = $(parent).find(".br3").html(),
          img = $(parent).find(".br2").html(),
          tpl = $("#comp"),
          tpl_close = tpl.find(".close"),
          tpl_img = tpl.find(".cmp1"),
          tpl_name = tpl.find(".cmp2")


   	 if(!input.attr("checked")) {
		el.css("background-position","0 0px");
		input.attr("checked", true)
        if ($("#compare").css('display')=="none") {
            $("#compare").show();
        }
        tpl_img.html(img);
        tpl_name.html(name);
        tpl_close.attr("id", "comp_close"+id)

        var b = tpl.clone().appendTo($("#compare_block"));
        b.attr("id", id);
        b.addClass("comp")
        b.fadeIn(300)
        set_ids()
	} else {
		el.css("background-position","0 -34px");
		input.attr("checked", false)

        compare_remove($("#comp_close"+id), 0)
	}
     return true;
}

function compare_remove(el, from_compare) {
    var el = el,
        from_compare = from_compare,
        id = el.attr("id").substring(10,el.attr("id").length)
        b = $("#"+id),

        check = $("#check"+id),
        input = check.find("input").eq(0)

    b.fadeOut(300, function(){
        b.remove()
        if (from_compare == 1) {
            check.css("background-position","0 -34px");
            input.attr("checked", false);
        }
        $(".broker-compare-" + id).remove()
        set_ids()

    });

}
function remove_from_compare(id) {
    var id = id
    $(".broker-compare-" + id).remove()
    compare_remove($("#comp_close"+id), 0)
}
function set_ids() {
    var ids = "";
    $(".comp").each(function(data){

            ids = ids + $(this).attr("id")  + ",";

    })
    if (ids=="") {
        $("#compare").hide();
    }
    $("#compare_ids").val(ids.substring(0, ids.length-1));
    
}

function load_statistic(id) {
    var id = id
    $("#broker_stat").parent(".drop2").hide();
    if (id>0) {
        $("#broker_stat").load("/broker_stat.html?id="+id, function(){
            
            var wi2 = parseInt($(".drop2").width()/2);
            $("#broker_stat").parent(".drop2").css("marginLeft", -wi2-200+"px")
            $("#broker_stat").parent(".drop2").show();
        });
    }
}

function add_comment(csrf, bid, html) {
    var csrf = csrf,
        bid = bid,
        parent = $("#parent_comment_id").val()

    $(".err").each(function(data){
         $(this).removeClass("error_field")
    });

    if ($("#id_name").val()==""){
        $("#er_name").addClass("error_field");
        $("#id_name").focus();
        return false;
    } else if ($("#id_email").val()=="") {
        $("#er_email").addClass("error_field");
        $("#id_email").focus();
        return false;
    } else if ($("#id_comment").val()=="") {
        $("#er_comment").addClass("error_field");
        $("#id_comment").focus();
        return false;
    } else if ($("#id_cap_1").val()==""){
        $("#er_cap_1").addClass("error_field");
        $("#id_cap_1").focus();
        return false;
    };

    $.ajax({
      url: "/" + html + ".html",
      type: "POST",
      cache: false,

      data: {
          name: $("#id_name").val(),
          email: $("#id_email").val(),
          comment: $("#id_comment").val(),
          cap_0: $("#id_cap_0").val(),
          cap_1: $("#id_cap_1").val(),

          parent: parent,
          broker: bid,
          csrfmiddlewaretoken: csrf
      },
      success: function(status){
          if (status == "done") {
              $("#id_cap_1").val('')
              $("#id_comment").val('')
              $("#parent_comment_id").val('')
            window.location.reload();
          } else {
            var errors = status.split(";");

            for (var el in errors) {
                $("#er_"+errors[el]).addClass("error_field")
            }
          }
      }
    });
    return false;
}

function add_review(csrf, bid) {
    var csrf = csrf,
        bid = bid

    $(".err").each(function(data){
         $(this).removeClass("error_field")
    });

    $.ajax({
      url: "/add_review.html",
      type: "POST",
      cache: false,

      data: {
          score: $("#id_score").val(),
          content: $("#id_content").val(),

          broker: bid,
          csrfmiddlewaretoken: csrf
      },
      success: function(status){
          
          if (status == "done") {
              $("#id_score").val('')
            window.location.reload();
          } else {
            var errors = status.split(";");

            for (var el in errors) {
                $("#er2_"+errors[el]).addClass("error_field")
            }
          }
      }
    });
    return false;
}

function check_search_field() {
    var val = document.getElementById('search_field').value
    if (val == 'Поиск брокера') {
        return false;
    } else if (val.length<3) {
        alert("Минимум три символа");
        return false;
    } else {
        return true;
    }

}

Number.prototype.padZero= function(len){
 var s= String(this), c= '0';
 len= len || 2;
 while(s.length < len) s= c + s;
 return s;
}

function getHours(hours, t_delta) {
    var t_delta = t_delta,
        h = hours + t_delta,
        hh = 0

    if (h<0) {
        hh = 24 + h
    } else if (h>24) {
        hh = h - 24
    } else {
        hh = h
    }

    return hh
}

function update_clock(hours, minutes) {

    var hours = hours,
        minutes = minutes,
        ny_hours = getHours(hours, -5),
        london_hours = hours,
        moscow_hours = getHours(hours, 4),
        hk_hours = getHours(hours, 8),
        sydney_hours = getHours(hours, 10)

    document.getElementById('ny_time').innerHTML = '<strong>Нью-Йорк</strong> ' + ny_hours.padZero() + ":" +  minutes.padZero()
    document.getElementById('london_time').innerHTML = '<strong>Лондон</strong> ' + london_hours.padZero() + ":" +  minutes.padZero()
    document.getElementById('moscow_time').innerHTML = '<strong>Москва</strong> ' + moscow_hours.padZero() + ":" +  minutes.padZero()
    document.getElementById('hk_time').innerHTML = '<strong>Гонконг</strong> ' + hk_hours.padZero() + ":" +  minutes.padZero()
    document.getElementById('sydney_time').innerHTML = '<strong>Сидней</strong> ' + sydney_hours.padZero() + ":" +  minutes.padZero()
}
function clockCounter() {
    var minutes = wt_minutes,
        seconds = wt_seconds,
        hours = wt_hours,
        seconds_delta = wt_interval
        interval = wt_interval * 1000

    seconds += seconds_delta

    if (seconds > 59) {
        minutes += 1
        seconds = 0
        if (minutes>59) {
            minutes = 0
            hours += 1
            if (hours>23) {
                hours = 0
            }
            update_clock(hours, minutes);
        }
        update_clock(hours, minutes)
    }
    wt_hours = hours,
    wt_minutes = minutes,
    wt_seconds = seconds

    var clock = setTimeout("clockCounter()", interval)
}

function world_time(time) {

    var time = time.split(":")
    wt_interval = 1
    wt_hours = parseInt(time[0]);
    wt_minutes = parseInt(time[1]);
    wt_seconds = parseInt(time[2]);

    var clock = setTimeout("clockCounter()", wt_interval*1000)

}

function feedback_form() {

    $("#forgot_popup").hide();
    $("#login_popup").hide();
    $("#reg_popup").hide();
    $("#feedback_popup").show();

}

function add_feedback(csrf) {
    var csrf = csrf

    $(".err").each(function(data){
         $(this).removeClass("error_field")
    });

    if ($("#id_fname").val()==""){
        $("#er_fname").addClass("error_field");
        $("#id_fname").focus();
        return false;
    } else if ($("#id_femail").val()=="") {
        $("#er_femail").addClass("error_field");
        $("#id_femail").focus();
        return false;
    } else if ($("#id_fcomment").val()=="") {
        $("#er_fcomment").addClass("error_field");
        $("#id_fcomment").focus();
        return false;
    } else if ($("#id_fcap_1").val()==""){
        $("#er_fcap_1").addClass("error_field");
        $("#id_fcap_1").focus();
        return false;
    };

    $.ajax({
      url: "/feedback.html",
      type: "POST",
      cache: false,

      data: {
          fname: $("#id_fname").val(),
          femail: $("#id_femail").val(),
          fcomment: $("#id_fcomment").val(),
          fcap_0: $("#id_fcap_0").val(),
          fcap_1: $("#id_fcap_1").val(),

          csrfmiddlewaretoken: csrf
      },
      success: function(status){
          if (status == "done") {
              $("#id_fcap_1").val('')
              $("#id_fcomment").val('')
              $("#fb_mform").hide();
              $("#fb_congr").show();
          } else {
            var errors = status.split(";");

            for (var el in errors) {
                $("#er_"+errors[el]).addClass("error_field")
            }
          }
      }
    });
    return false;
}
