/* Fix for IE6 background-image flicker
* See http://www.mister-pixel.com/#Content__state=is_that_simple
*/

try {
    document.execCommand('BackgroundImageCache', false, true);
} catch(err) {}


//globals
var searchTeasers = [];
searchTeasers['mainSearch'] = '';
var lastHL = '';
var limit = '';

$(document).ready(function() {
    var page = $('body').attr('id');

    switch(page) {
        case 'mainPage':
          setMainPage();
          break;
        case 'firmMainPage':
          setFirmMainPage();
          break;
        case 'newsPage':
          setNewsPage();
          break;
        case 'firmRegister':
          setFirmRegister();
          break;
        case 'firmBasic':
          setFirmRegister();
          break;
        case 'firmSettings':
          setFirmSettings();
          break;
        case 'userRegister':
          setUserRegister();
          break;
        default: common();
    }
    $("a[rel*='external']").click(function(){
         pageTracker._trackPageview('/outgoing/'+ $(this).attr('href'));
    });
});

function setMainPage() {
    $('#mainPageTabs > ul').tabs();
    handleFormSuggest('searchFirmsWhat');
    handleFormSuggest('searchFirmsLoc');
    handleEmptyForms('searchFirms', 'searchFirmsWhat');

    common();
}
function setFirmMainPage() {
    handleFormSuggest('searchMainFirmsWhat');
    handleFormSuggest('searchMainFirmsWhere');
    handleEmptyForms('searchFirms', 'searchMainFirmsWhat');

    common();
}
function setNewsPage() {
    common();
}
function setFirmSettings() {
    handleForm('firmChangePassForm', 'errorBox1');
    handleForm('firmChangeEmailForm', 'errorBox2');
    handleForm('firmCancelAccountForm', 'errorBox3');

    common();
}
function setUserRegister() {
    handleCityCountry();
    common();
}
function setFirmRegister() {
    handleCityCountry();
    common();
}

function handleCityCountry () {

    if($('#CRegionId').val()) {
        //load regions
        $("#CRegion").load (path + '/ajax/regionsoptions?idRegion='+$('#CRegionId').val());
        $("#CRegion").attr('disabled', '');
        handleCityRegion ();
    }

    if($('#CRCityId').val()) {
        //load regions
        $("#CRegion").load (path + '/ajax/regionsoptions?idCity='+$('#CRCityId').val());
        $("#CRegion").attr('disabled', '');

        //load cities
        $("#CRCity").load (path + '/ajax/citiesoptions?idCity='+$('#CRCityId').val());
        $("#CRCity").attr('disabled', '');
        handleCity ();

        handleCityRegion ();
    }

    if($('#country').val() && !$('#CRCityId').val()){
        $("#CRegion").load (path + '/ajax/regionsoptions?idc='+$('#country').val());
        $("#CRegion").attr('disabled', '');

        handleCityRegion ();
    }

    $('#country').bind('change', function() {

        if($('#country').val() == ''){

            $('#CRegion :selected').text('Proszę wybrać najpierw kraj');
            $("#CRegion").attr('disabled', 'disabled');
            $('#CRCity :selected').text('Proszę wybrać najpierw kraj');
            $("#CRCity").attr('disabled', 'disabled');
            $('#CRegion').bind('change', function() {});

        } else {

            $("#CRegion").load (path + '/ajax/regionsoptions?idc='+$('#country').val());
            $("#CRegion").attr('disabled', '');

            handleCityRegion ();

        }

    })

}
function handleCityRegion () {

    $('#CRegion').bind('change', function() {
    	
        $('#CRegionId').val($('#CRegion').val());

        $("#CRCity").attr('disabled', 'disabled');

        if($('#CRegion').val() == ''){

            $('#CRCity').val('');
            $('#CRCity :selected').text('Proszę wybrać najpierw region');
            $("#CRCity").attr('disabled', 'disabled');
            $('#CRCityId').val('');
        } else {

            $("#CRCity").load (path + '/ajax/citiesoptions?idr='+$('#CRegion').val());
            $("#CRCity").attr('disabled', '');
            handleCity ();
        }

    });
}
function handleCity () {
    $('#CRCity').bind('change', function() {

        $('#CRCityId').val($('#CRCity').val());
        

    });
}

/*
function handleCityCountry () {
    $("#suggestCity").autocomplete(path + "/ajax/cities", {
        width: 310,
        selectFirst: false,
        minChars: 1,
        matchContains: false,
        mustMatch: true,
        matchSubset: false,
        formatItem: function(row, i, max) {
            return row[1];
        },
        extraParams:  {
            country:  ''
        }
    });
    $("#suggestCity").result(function(event, data, formatted) {
        if (data) {
            var cos = document.createElement('div');
            $(cos).html(data[1]);
            $('#citySearchInfo').html('Miasto zostało wybrane');
            return $('#city').val($('span', cos).attr('id'));
        }
    });
    $('#country').bind('change', function() {
        if($('#country').val() == ''){
            $('#city').val('');
            $("#suggestCity").val('Proszę wybrać najpierw kraj');
            $("#suggestCity").attr('disabled', 'disabled');
        } else {
            $("#suggestCity").val('');
            $("#suggestCity").attr('disabled', '')
        }
        $("#suggestCity").flushCache();
        $('#suggestCity').setOptions({
            extraParams:  {
                country:  $("#country").val()
            }
        });
    })
    $('#suggestCity').bind('focus', function(e) {
        displayInputInfo('#city')
    })
}
*/

function handleForm(formName, errorBox) {
    $("#" + formName).validate({
        debug: false,
        meta: "validate",
        errorLabelContainer: $("#" + errorBox),
        wrapper: 'li',
        onsubmit: true,
        onfocusout: false,
        onkeyup: false,
        onclick: false,
        focusInvalid: false,
        highlight: function(element, errorClass) {
            var ele = '#hl' + $(element).attr('id');
            if(lastHL != '') {
                $(lastHL).css('visibility', 'hidden');
                lastHL = '';
            }
            $(ele).css('visibility', 'visible').addClass('inputError');
            $(ele + '> span.hlinfo').css('display', 'none');
            $(ele + '> span.hlerror').css('display', 'inline');
          },
        unhighlight: function(element, errorClass) {
            var ele = '#hl' + $(element).attr('id');
            $(ele).css('visibility', 'hidden').removeClass('inputError');
            $(ele + '> span.hlerror').css('display', 'none');
        }
    });
    $(".showInfoHL").bind('focus', function(e) {
        displayInputInfo(this);
    });
}
function displayInputInfo(ele) {
        if(lastHL != '') {
            $(lastHL).css('visibility', 'hidden');
        }
        lastHL = '#hl' + $(ele).attr('id');
        $(lastHL).removeClass('inputError').css('visibility', 'visible');
        $(lastHL + '> span.hlinfo').css('display', 'inline');
        $(lastHL + '> span.hlerror').css('display', 'none');
}
function common() {
    handleFormSuggest('mainSearch');
    handleEmptyForms('topSearch', 'mainSearch');

    if($('#sectionSearchForm').get()) {
        handleFormSuggest('sectionSearch');
        handleEmptyForms('sectionSearchForm', 'sectionSearch');
    }
    setMenu();

    $('#print').bind('click', function(e){
        window.open ($(this).attr('href'), "mywindow","status=0,toolbar=0,width=720,height=600,resizable=1,scrollbars=1");
        return false;
    });

    $("form.handleForm").each(function (i) {
       handleForm($(this).attr('id'), 'errorBox');
     });

}
function handleFormSuggest(inputId) {
    searchTeasers[inputId] = $('#' + inputId).attr('value');
    $('#' + inputId).bind('click', function(e){
        if( ($(this).attr('value') + 'a') == (searchTeasers[inputId]  + 'a')) {
            $(this).attr('value','').css('color', '#222');
        }
    }).bind('blur', function(e) {
        if($(this).attr('value') == '') {
            $(this).attr('value', searchTeasers[inputId]).css('color', '#888');;
        }
    });
}

function handleEmptyForms(formId, inputId) {
    $('#' + formId).bind('submit', function(e){
        if( $('#' + inputId).attr('value') == '' || $('#' + inputId).attr('value') == searchTeasers[inputId]) {
            alert('Proszę podać frazę do wyszukania');
            return false;
        } else {
            return true;
        }
    })
}

function setMenu() {
    $('li.menuLink').bind('mouseenter', function (e) {
        var ele = $(this);
        var offset = ele.offset();
        var vector = 0;
        if ($.browser.mozilla) {
            vector = 1;
        }
        $('#submen' + ele.attr('id')).css('top', offset.top + $(this).height()+1).css('left', offset.left + vector).show();
    }).bind('mouseleave', function (e) {
        var ele = $(this);
        $('#submen' + ele.attr('id')).hide();
    });
}

function addToEventIn (isUserLogin, eid) {
    if (isUserLogin) {
        $.ajax({
           type: "POST",
           url: path + "/ajax/addtoeventin",
           data: "eventId="+eid,
           success: function(add){
               if(add)
             alert( "Zostałeś dodany do listy");
           }
         });
    } else {
        alert('Opcja dostępna po zalogowaniu');
    }
}

function addToEventLookAt (isUserLogin, eid) {
    if (isUserLogin) {
        $.ajax({
           type: "POST",
           url: path + "/ajax/addtoeventlookat",
           data: "eventId="+eid,
           success: function(add){
               if(add)
             alert( "Zostałeś dodany do listy");
           }
         });
    } else {
        alert('Opcja dostępna po zalogowaniu');
    }
}

function addToFriendList (isUserLogin, fid) {
    if (isUserLogin) {
        $.ajax({
           type: "POST",
           url: path + "/ajax/addfriend",
           data: "friendId="+fid,
           success: function(add){
               if(add)
             alert( "Zaproszenie zostało wysłane");
           }
         });
    } else {
        alert('Opcja dostępna po zalogowaniu');
    }
}

function removefriendList (isUserLogin, fid, userName) {
    if (isUserLogin) {
        $.ajax({
           type: "POST",
           url: path + "/ajax/removefriend",
           data: "friendId="+fid,
           success: function(remove){
               if(remove){
                 alert( "Znajomy został usunięty");
                 location.href=path+'/profil/'+userName+'/znajomi';
            }else
                 alert( "Tylko właściciel tego profilu może usuwać swoich znajomych");
           }
         });
    } else {
        alert('Opcja dostępna po zalogowaniu');
    }
}