// ========= (c)2011 :: html & css & jquery coding :: ЯRIK - www.csska.com  =========


$(document).ready(function() {
    if (!$.browser.msie) {
        $(".comment").corner("5px");
    }
});



// =========================================================================  Search

$(document).ready(function() {
    var search_string = $("#hsearch input[name=search_string]").val();
    $("#hsearch input[name=search_string]").focus(function() {
        if ($(this).val() == search_string) {
            $(this).val('');
        }
    });
    $("#hsearch input[name=search_string]").blur(function() {
        if ($(this).val() == '') {
            $(this).val(search_string);
        }
    });
    $("#hsearch a").click(function() {
        $(this).parent().submit();
        return false;
    });
});


function GetInfoByMetroStation(_name) {
    $.post("/index.php", { CallModule: "search_by_metro", name: _name }, function(_data) {
        $("#addresses").html(_data);
        $('html, body').stop().animate({
            scrollTop: $("#addresses").offset().top
        }, 1000);
    });
}



// =========================================================================  select

$(document).ready(function() {
    $('#htown select').change(function() {
        stext = $('#htown select :selected').text();
        $('#htown p span').html(stext);
        //		$(this).parent().submit();
    });
});



// =========================================================================  addcomment

$(document).ready(function() {
    $("#sendcomment").click(function() {
        $(this).parent().submit();
        return false;
    });
});

// ------------------------------------------------------------------- LOGIN Window


$(document).ready(function() {

    $('#loginbt, #loginbt2').live("click", function() {
        $.post('/login_form.html', { ids: 'f1' }, function(data) {
            window.scrollBy(0, -5000000);
            $('body').append(data);
            $('#loginwin').fadeIn();
            $('body').append('<div id="fade"></div>');
            $('#fade').css({ 'filter': 'alpha(opacity=80)' }).fadeIn();
        });
        return false;
    });

    $('#regbt, #regbt2').live("click", function() {
        $.post('/registration_form.html', { ids: 'f1' }, function(data) {
            window.scrollBy(0, -5000000);
            $('body').append(data);
            $('#loginwin').fadeIn();
            $('body').append('<div id="fade"></div>');
            $('#fade').css({ 'filter': 'alpha(opacity=80)' }).fadeIn();

        });
        return false;
    });

    $("#logout").live("click", function() {
        LogOut();
    });

    $('a.loginwin_close, #fade').live('click', function() {
        $('#fade , #loginwin').fadeOut(function() {
            $('#fade').remove();
            $('#loginwin').remove();
        });
        return false;
    });
});

function Login() {
    var login = $("#loginwin input[name='login']").val();
    var password = $("#loginwin input[name='password']").val();
    $.post("/", { CallModule: "ajax_login", login: login, password: password }, function(_data) {
        if (_data == "0") {
            $("#messagelogin").html("<i>Не верная комбинация</i>");
        }
        else {
            $("#hlogin").empty();
            $("#hlogin").html(_data);
            $('#fade').remove();
            $("#loginwin").remove();
            window.location = window.location;
        }
    });
}

function LogOut() {
    $.post("/", { CallModule: "ajax_login", action: "logout" }, function(_data) {
        $("#hlogin").empty();
        $("#hlogin").html(_data);
        window.location = window.location;
    });
}

function ShowRemember() {
    $("#loginwin h2").html("Восстановление пароля");
    $("#lost_pass").remove();
    $("#loginform1").hide();
    $("#remember_pass_form").show();
}

function Remember() {
    var login = $("#remember_pass_form input[name='login']").val();
    $.post("/", { CallModule: "remember_pass", login: login }, function(_data) {
        if (_data == "1") {
            $('#fade').remove();
            $("#loginwin").remove();
        }
        else {
            $("#message_pass").html("Логин не найден в базе.");
        }
    });
}

function Registration() {
    var fields = $("#regform1 input");
    var fields_arr = new Object();
    for (var i = 0; i < fields.length; i++) {
        var name = fields.eq(i).attr("name");
        $(fields_arr).attr(name, fields.eq(i).val());
    }
    fields_arr.CallModule = "a_reg";
    fields_arr.registrationForm = 1;
    $.post("/", fields_arr, function(_data) {
        switch (_data) {
            case "1":
                {
                    window.location = window.location;
                } break;
            case "2":
                {
                    $("#message_pass").html("Существующий логин.");
                } break;
            default:
                {
                    $("#regform1 span").css("color", "");
                    var fields = _data.split(",");
                    for (var i = 0; i < fields.length; i++) {
                        $("#regform1 input[name='" + fields[i] + "']").parent().css("color", "red");
                    }
                }
        }
    });
}


// =========================================================================  findfoto

$(document).ready(function() {
    var src_str = $("#findfoto input[name=findfototext]").val();
    $("#findfoto input[name=findfototext]").focus(function() {
        if ($(this).val() == src_str) {
            $(this).val('');
        }
    });
    $("#findfoto input[name=findfototext]").blur(function() {
        if ($(this).val() == '') {
            $(this).val(src_str);
        }
    });
    $("#findfotobt").click(function() {
        $(this).parent().submit();
        return false;
    });
    var max_height = 0;
    $(".afis").each(function(_index) {
        if ($(this).height() > max_height) max_height = $(this).height();
    });
    $(".afis").height(max_height);

    var max_height_experts = 0;
    $(".exps").each(function(_index) {
        if ($(this).height() > max_height_experts) max_height_experts = $(this).height();
    });
    $(".exps").height(max_height_experts);

    var max_height_adress = 0;
    $(".adress").each(function(_index) {
        if ($(this).height() > max_height_adress) max_height_adress = $(this).height();
    });
    $(".adress").height(max_height_adress);
});


//--------------------------------------------------------------------- карты
var map = null;
var geocoder = null;
var addresses = new Array();
var all_addresses = new Array();
var stations_types = new Array();
var last_point;

var curr_addr = 0;

function AddAddressToArr(_address, _type, _message) {
    all_addresses.push(_address);
    addresses[_address] = new Array(_type, _message);
}

function showAddressReq() {
    if (curr_addr < all_addresses.length) {
        if (geocoder) {
            geocoder.getLatLng(
      all_addresses[curr_addr],
      function(point) {
          if (!point) {
              /*alert(_address + " не найден");*/
          } else {
          last_point = point;
          addresses[all_addresses[curr_addr]][2] = point;
              map.addOverlay(createMarker(point, addresses[all_addresses[curr_addr]][1], false));
          }
          curr_addr++;
          showAddressReq();
      }
    );
        }
    }
}
function OnMetroMap(_station_name, _type) {
    var data = $("html").data("moscow.birman");
    var stations = data.stations;

    stations_types[_station_name] = _type;

    for (var i in stations) {
        if (stations[i].name == trim(_station_name)) {
            $("#metro").append("<div class=\"metro_station\" style='top:" + (stations[i].y1 - 3) + "px; left:" + (stations[i].x2) + "px' onclick='GetInfoByMetroStation(\"" + trim(_station_name) + "\")'><img src='/images/fujifilm_logo_i.png' alt=''></div>");
            break;
        }
    }
}

function ShowStationsByType(_type) {
    $(".metro_station").remove();
    for (var station in stations_types) {
        if (stations_types[station] == _type || _type == -1) {
            OnMetroMap(station, _type);
        }
    }
}

function showAddressNoInfo(_address, _zoom) {
    if (_zoom == null) _zoom = 15;
    if (geocoder) {
        geocoder.getLatLng(
      _address,
      function(point) {
          if (!point) {
              /*alert(_address + " не найден");*/
          } else {
              map.setCenter(point, _zoom);
          }
      }
    );
    }
}

function ShowLastPoint() {
    map.setCenter(last_point, 15);
}

function ShowCenter() {
    setTimeout("showAddressNoInfo('Москва, ул. Тверская', 10)", 3000);
}

function showAddress(_address, _type, _message, _goto) {
    if (_goto == null) _goto = false;
    if (geocoder) {
        geocoder.getLatLng(
      _address,
      function(point) {
          if (!point) {
              /*alert(_address + " не найден");*/
          } else {
              last_point = point;
              addresses[_address] = new Array(_type, _message, point);
              if (_goto) map.setCenter(point, 11);
              map.addOverlay(createMarker(point, _message, _goto));
          }
      }
    );
    }
}

function ShowByType(_type) {
    map = new GMap2(document.getElementById("print_points"));
    map.addControl(new GSmallMapControl());
    for (var address in addresses) {
        if ((addresses[address][0] == _type || _type == -1) && addresses[address][2] != null) {
            //map.setCenter(addresses[address][2], 11);
            map.addOverlay(createMarker(addresses[address][2], addresses[address][1]));
            //last_point = addresses[address][2];
        }
    }
    ShowCenter();
    ShowStationsByType(_type);
}

function createMarker(_point, _message, _show) {
    if (_show == null) _show = false;
    var marker = new GMarker(_point);
    GEvent.addListener(marker, "mouseover", function() {
        map.openInfoWindowHtml(_point, _message);
    });
    if (_show) map.openInfoWindowHtml(_point, _message);
    return marker;
}

function gotoPointer(_address) {
    if (geocoder) {
        geocoder.getLatLng(
          _address,
          function(point) {
              if (!point) {
                  /*alert(_address + " не найден");*/
              } else {
                  map.setCenter(point, 14);
                  map.openInfoWindowHtml(point, addresses[_address][1]);
              }
          }
        );
    }
}

function ChangeMapView(_side) {
    if (_side == 0) {
        $("#map").show();
        $("#metro").hide();
    }
    else {
        $("#map").hide();
        $("#metro").show();
    }
}


function trim(str, charlist) {
    // Strips whitespace from the beginning and end of a string  
    // 
    // version: 1107.2516
    // discuss at: http://phpjs.org/functions/trim
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: mdsjack (http://www.mdsjack.bo.it)
    // +   improved by: Alexander Ermolaev (http://snippets.dzone.com/user/AlexanderErmolaev)
    // +      input by: Erkekjetter
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: DxGx
    // +   improved by: Steven Levithan (http://blog.stevenlevithan.com)
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // *     example 1: trim('    Kevin van Zonneveld    ');
    // *     returns 1: 'Kevin van Zonneveld'
    // *     example 2: trim('Hello World', 'Hdle');
    // *     returns 2: 'o Wor'
    // *     example 3: trim(16, 1);
    // *     returns 3: 6
    var whitespace, l = 0,
        i = 0;
    str += '';

    if (!charlist) {
        // default list
        whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";
    } else {
        // preg_quote custom list
        charlist += '';
        whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
    }

    l = str.length;
    for (i = 0; i < l; i++) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(i);
            break;
        }
    }

    l = str.length;
    for (i = l - 1; i >= 0; i--) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(0, i + 1);
            break;
        }
    }

    return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}

function EventAction(_object, _id) {
    var action = $(_object).attr("action");
    if (action == 1) {
        WantToGo(_object, _id);
    }
    else {
        DontWantToGo(_object, _id);
    }
}

function WantToGo(_object, _id) {
    $.post("/", { CallModule: "want_to_go", pid: _id, action: 1 }, function(_data) {
    $("#wtg").html(_data);
        //$(_object).attr("action", 0);
        //$(_object).find("img").attr("src", "/images/nono.png");
    });
}

function DontWantToGo(_object, _id) {
    $.post("/", { CallModule: "want_to_go", pid: _id, action: 0 }, function(_data) {
    $("#wtg").html(_data);
        //$(_object).attr("action", 1);
        //$(_object).find("img").attr("src", "/images/gogo.png");
    });
}
