/* ***********************************************************************
   @Nazwa:   /js/main.js
   @Autor:   Tomasz Łabacki
   @Email:   tomasz@labacki.com
   @www:     http://labacki.com
   @Data:    2 września 2010 17:12
   @Updated: 5 września 2010: 17:24
   @Opis:    Opis podstawowych funkcji.
   @License: Licensed to Agencja Reklamowa MiroArt (http://miroart.pl)
   @Require: jQuery 1.4 or above
   @Language: PL
*********************************************************************** */

//KONFIGURACJA
var animate_search_bookmarks=true;       //animacja po kliknięciu na zakładki wyszukiwarki (boolean)
var animate_search_delay=75;             //czas animacji w ms (int)

$(document).ready(function(){//gdy dokument (tekst) zostanie wczytany
    obsluga_wyszukiwarki();  //raguje na zdarzenia z wyszukiwarki
    menu_effect();           //podrasowanie menu górnego - szerokość submenu
});

$(window).load(function(){   //gdy całość strony zostanie wczytana... poprawiamy img i wysokość
    popraw_img();            //dodaje znaczniki width i height dla img, jesli brakuje
    wyrownaj_menu();         //w #content oba główne divy będą tej samej wysokosci
    wyrownaj_liste();        //w liście ofert wyrównuje do dołu linki ("np. dodaj do schowka")
});

function popraw_img(){
    var width, height;
    $("img").each(function(index,elem){
            width=$(elem).attr("width");
            height=$(elem).attr("height");
            if(width===undefined) {$(elem).attr("width",$(elem).width());}
            if(height===undefined) {$(elem).attr("height",$(elem).height());}
    });
}

function obsluga_wyszukiwarki(){
    $("#bookmark_first").click(function(){
        $(this).css("color","#000");
        $("#bookmark_second").css("color","#bbb");
        $(this).parent().css("margin","0 7px 0 4px");
        $(this).parent().parent().css("background-position","0 0");

        if(animate_search_bookmarks){
            if($("#bookmark_first_field").css("display")=="none"){
                $("#bookmark_second_field").fadeOut(animate_search_delay,function(){$("#bookmark_first_field").fadeIn("fast");});
            }
        } else {
            $("#bookmark_first_field").show();
            $("#bookmark_second_field").hide();
        }
    });
    $("#bookmark_second").click(function(){
        $(this).css("color","#000");
        $("#bookmark_first").css("color","#bbb");
        $(this).parent().css("margin","0 4px 0 7px");
        $(this).parent().parent().css("background-position","0 -160px");

        if(animate_search_bookmarks){
            if($("#bookmark_second_field").css("display")=="none"){
                $("#bookmark_first_field").fadeOut(animate_search_delay,function(){$("#bookmark_second_field").fadeIn("fast");});
            }
        } else {
            $("#bookmark_second_field").show();
            $("#bookmark_first_field").hide();
        }
    });
}

function menu_effect(){//ustalenie szerokości submenu
  $('ul#navi_bar > li').each(function(){
      var width=$(this).outerWidth()-2;
      $(this).find("ul li a").css("width",width);
  });
}

function wyrownaj_menu(){//dostosowanie wysokości panelu lewego i prawego do środkowego
    var content_left=$("div#content_left_middle").height();
    var content_right=$("div#content_right_middle").height();
    var max=Math.max(content_left,content_right);
    $("div#content_left_middle,div#content_right_middle").css("height",max);
}

function wyrownaj_liste(){//dostosowanie wysokości linków "dodaj do schowka" i "zobacz ofertę", aby były na dole okienka
    var height_img, height_info, height_links;
    $("ul#offer_list li").each(function(index,elem){
        height_img=$(elem).find(".offer_img").height();
        height_info=$(elem).find(".offer_shortinfo").height();
        height_links=$(elem).find(".shortinfo_links").height();
        if(height_img>height_info) {$(elem).find("p.shortinfo_links").css("margin-top",height_img-height_info-height_links);}
    });
}



$(document).ready(function(){

    //uruchomienie PrettyPhoto
    $("a[rel=externform], a[rel=prettyPhoto[galeria]]").prettyPhoto({theme: 'facebook'});

    //włączenie hoverImg na obrazkach z menu górnego
    $("#graphic_menu img").hoverImg();

    //dostosowanie wysokości panelu lewego i prawego do środkowego
    var content_center=$("div#content_center_middle").height();
    var content_left=$("div#content_left_middle").height();
    var content_right=$("div#content_right_middle").height();
    var max=Math.max(content_center,content_left,content_right);
    $("div#content_center_middle,div#content_left_middle,div#content_right_middle").css("height",max);

    //wysyłka i obsługa formularza do newslettera
    $("form#newsletter").submit(sprawdz_formularz_newslettera);
    $("form#newsletter select").change(sprawdz_formularz_newslettera);
    $("form#newsletter input").keyup(sprawdz_formularz_newslettera);

	// Wybór szerokości galerii
    var content_width=$(window).width();
    if (content_width>1190) {$("a[rel=externform]") .each(function() { this.href = this.href.replace('widthgal=small', "widthgal=bigger"); });}
	
    // Walidacja formularza
    $("form.sprawdz").submit(function(){
        // na początku zakładamy, że błędu nie ma
        var error_form=false;
        
        $(this).find("input,textarea,select").each(function(){
            // id elementu formularza
            var id=$(this).attr("id");

            // szukamy treść <label> powiązanego z tym elementem
            var tresc_label=$("form.sprawdz label[for="+id+"]").text();

            // czy ta treść zawiera gwiazdkę?
            var szukane_reg=new RegExp("\\*","i");
            if(szukane_reg.test(tresc_label)){
                // OK, ten element formularza musi być wypełniony
                if( ($(this).is("input") && $(this).val()=="") ||
                    ($(this).is("textarea") && $(this).val()=="") ||
                    ($(this).is("select") && $(this).val()=="none")) {
                        $(this).addClass("error");
                        error_form=true;
                } else {$(this).removeClass("error");}

                // A jeśli element to checkbox, to zaznaczamy jego <label> jako error
                if ($(this).attr("type")=="checkbox" && $("input#"+id+":checked").val()===undefined){
                    $("form.sprawdz label[for="+id+"]").addClass("error");
                } else {$("form.sprawdz label[for="+id+"]").removeClass("error");}
            }
        });
        return !error_form;
    });
});

function emailValidator(address){
    var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/i;
    return emailExp.test(address)
}
function sprawdz_formularz_newslettera(){
        var email=$("form#newsletter").find("input[name=email]");
        var imie=$("form#newsletter").find("input[name=imie]");
        var temat=$("form#newsletter").find("select[name=temat]");
        var error=false;
        if(!emailValidator(email.val())) {error=true; $(email).css("border-color","#FF0000");} else{$(email).css("border-color","");}
        if(trim(imie.val())=="" || trim(imie.val())=="Imię") {error=true; $(imie).css("border-color","#FF0000");} else{$(imie).css("border-color","");}
        if(temat.find("option:selected").val()=="none") {error=true; $(temat).css("border-color","#FF0000");} else{$(temat).css("border-color","");}

        if(!error){
            //nie ma błedu - mozna kontynuować, np. jakiegoś ajaxa tutaj
            //zapodać, lub zostawić po prostu `return true` i pozwolić działać
            //mechanizmom przeglądarki i wysłać zwyczajnie POSTem
            var temat = $("form#newsletter").find("select[name=temat]").val();
            var email = $("form#newsletter").find("input[name=email]").val();
            var imie = $("form#newsletter").find("input[name=imie]").val();
			$('#newsletter').load("/newsletter_add_mail.php5?mail="+email+"&imie="+imie+"&topic="+temat);
			return false;

        } else{
            //bład jest
            return false;
        }
}

function trim(str) {
    // prawostronnie
    str=str.replace(new RegExp("[\\s]+$", "g"), "");
    // lewostronnie
    str=str.replace(new RegExp("^[\\s]+", "g"), "");
    // wynik
    return str;
}

function bookmark()
{
	var title="Cemarol - Sprzedaż maszyn i części rolniczych"
	var url="http://www.cemarol.com.pl"

	if (window.sidebar) window.sidebar.addPanel(title, url,"");

	else if( window.opera && window.print )
	{
	var mbm = document.createElement('a');
	mbm.setAttribute('rel','sidebar');
	mbm.setAttribute('href',url);
	mbm.setAttribute('title',title);
	mbm.click();
	}

	else if( document.all ) window.external.AddFavorite( url, title);
}



historyArray=[];

var ua = navigator.userAgent.toLowerCase();
isIE = ((ua.indexOf("msie") != -1) && (ua.indexOf("opera") == -1))

function checkHistory()
{
	if(location.hash.replace('#', '')!=lastHistory&&location.hash.replace('#', '')!='top') { content.load(location.hash.replace('#', '')); }
}

function historyBack()
{
	var ua = navigator.userAgent.toLowerCase();
	isIE = ((ua.indexOf("msie") != -1) && (ua.indexOf("opera") == -1));
	if(!isIE||historyArray.length==0) { history.back(); }
	else
	{
		var temp = lastHistory;
		historyArray.pop();
		if(historyArray[historyArray.length-1]!='')
		{
			content.load(historyArray[historyArray.length-1]);
		}
		historyArray.pop();
		lastHistory=temp;
	}
}

