//doc ready...
$(function(){
    
    $("#footer").css("top", $(document).height());
    
    $('form#extended_searchform input[type="text"], form#extended_searchform input[type="password"], form#extended_searchform select, form.regform select, form.regform .input[type="text"], #extended_searchform select, form.regform .input[type="password"]")').not(".tel").css({
        backgroundColor:'#E4EADD',
        border:'medium none',
        height:'22px',
        left:'200px',
        marginBottom:'8px',
        padding:'3px 0 0 3px',
        position:'absolute',
        top:'-3px',
        width:'310px'
    });
    
    $(".worker_profile .ratebox").each(function() {
        $(this).height($(this).parent().height() - 45);
    });
    
    $("#loginform #username").click(function() {
        if($(this).val() == "Felhasználónév")
            $(this).val("");    
    }).blur(function() {
        if($(this).val() == "")
            $(this).val("Felhasználónév");
    });
    $(".box_left span#pwlabel").click(function() {
        $(this).hide();
        $("#loginform #password").focus();
    });
    $("#loginform #password").blur(function() {
        if($(this).val() == "") 
            $(".box_left span#pwlabel").show();
    }).focus(function() {
        $(".box_left span#pwlabel").hide();
    });
    
    $("#no_rate").toggle(function() {
        $(this).text("(értékelteket)").css({bottom:"0px", left: "-10px"});
        $(".starsi img").hide();
        $("input[name=rate_value]").val(0);        
    }, function() {
        $(this).text("(mindet)").css({bottom:"3px", left: "0px"});
        $(".starsi img").show();
        $("input[name=rate_value]").val(1);
    });
    
    function fixPng() {
        var arVersion = navigator.appVersion.split("MSIE")
        var version = parseFloat(arVersion[1])
        
        if ((version >= 5.5 && version < 7) && (document.body.filters)) 
        {
           for(var i=0; i<document.images.length; i++)
           {
              var img = document.images[i]
              var imgName = img.src.toUpperCase()
              if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
              {
                 var imgID = (img.id) ? "id='" + img.id + "' " : ""
                 var imgClass = (img.className) ? "class='" + img.className + "' " : ""
                 var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
                 var imgStyle = "display:inline-block;" + img.style.cssText 
                 if (img.align == "left") imgStyle = "float:left;" + imgStyle
                 if (img.align == "right") imgStyle = "float:right;" + imgStyle
                 if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
                 var strNewHTML = "<span " + imgID + imgClass + imgTitle
                 + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
                 + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                 + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
                 img.outerHTML = strNewHTML
                 i = i-1
              }
           }
        }
    }fixPng();
    
    var noClear = false;
    $(".starsi img").mouseover(function() {
        //if(!noClear) {
            var starNum = $(".starsi img").index(this)+1;
            $(".starsi img").each(function(){  $(this).attr("src","images/star_off.png") });
            $(".starsi img").slice(0, starNum).attr("src","images/star_on.png");
        //}                                                      
    }).click(function(e) {
        //$(".starsi img").each(function(){  if(!noClear) $(this).attr("src","images/star_off.png") });
        if(e.target.id == "first") $(this).attr("src","images/star_off.png");
        $("input[name=rate_value]").val($(".starsi img[src=images/star_on.png]").length);
    }).mouseout(function(){
        selImg=$("input[name=rate_value]").val();
        $(".starsi img").each(function(){  $(this).attr("src","images/star_off.png") });
        $(".starsi img").slice(0, selImg).attr("src","images/star_on.png");
        //(noClear) ? noClear = false : noClear = true;
        //noClear = true;
    });
    
    if($.browser.msie) {
        /*$(".box_left").each(function() {
            $(this).height($(this).height()-20);
        });
        $(".box_center").each(function() {
            $(this).height($(this).height()-10);
        });*/ 
        $(".box_right").each(function() {
            $(this).height($(this).height()-10);
        });
    }
    
});
//...ready end

function loadProfessions(setAll) {
    $.post("index.php?content=ajax&cmd=loadprofessions", 
        { parentid:$("#profession_group").val(), setall:setAll }, 
        function(response) {
            if($("select#profession")) {
                $("select#profession").remove();    
            }
            $("label[for=profession]").append(response);
            $("#profession").effect("highlight", {}, 1000).focus();     
    });
}

function loadCities(setAll) {
    $.post("index.php?content=ajax&cmd=loadcities", 
        { countryid:$("#country").val(), setall:setAll }, 
        function(response) {
            if($("select#cities")) {
                $("select#cities").remove();    
            }
            $("label[for=cities]").append(response);
            $("#cities").effect("highlight", {}, 1000).focus();     
    });
}

function logBoxInput() {
    $("#loginform #username").click(function() {
        if($(this).val() == "Felhasználónév")
            $(this).val("");    
    }).blur(function() {
        if($(this).val() == "")
            $(this).val("Felhasználónév");
    });
    $(".box_left span#pwlabel").click(function() {
        $(this).hide();
        $("#loginform #password").focus();
    });
    $("#loginform #password").blur(function() {
        if($(this).val() == "") 
            $(".box_left span#pwlabel").show();
    }).focus(function() {
        $(".box_left span#pwlabel").hide();
    });
}

function login() {
    $.post(
        "index.php?content=user&cmd=login", 
        {un : $("#loginform #username").val(), pass:$("#loginform #password").val()}, 
        function(r) {
            $(".box_left:eq(0)").html(r);
            logBoxInput();
        }
    );
    return false;
}

function removeItem(originalArray, itemToRemove) {
    var j = 0;
    while (j < originalArray.length) {
    
        if (originalArray[j] == itemToRemove) {
            originalArray.splice(j, 1);
    } else { j++; }
}
    
    return originalArray;
}

var proList = new Array();
function addProList() {
    
    var pin = false;
    for(i=0;i<proList.length;i++) {
        if(proList[i] == $("#pro_expert").val())
            pin = true;
    }
    
    if($("#pro_expert").val() > -1 && !pin) {
        if($("#prolist span.items").text()=="-nincs")$("#prolist span.items").text("");   
        $("#prolist span.items").append('&nbsp;<a href="javascript:void(0)" onclick="$(this).remove();removeProList(' +$("#pro_expert").val()+ ')">' +$("#pro_expert").children("[@selected]").text()+ '</a>');
        proList.push($("#pro_expert").val());
        $("#prolist").effect("highlight", {}, 1000);  
    }
}

function removeProList(id) {
    removeItem(proList, id);
    eval('$("input[name=prolistval]").val($("input[name=prolistval]").val().replace(/'+id+'/, ""));');
    if($("#prolist span.items").text() == " ")$("#prolist span.items").text("");    
    if($("input[name=prolistval]").val() == "|")$("input[name=prolistval]").val("");    
}

var contraList = new Array();
function addContraList() {
    
    var pin = false;
    for(i=0;i<contraList.length;i++) {
        if(contraList[i] == $("#contra_expert").val())
            pin = true;
        
    }
    
    if($("#contra_expert").val() > -1 && !pin) {
        if($("#contralist span.citems").text()=="-nincs")$("#contralist span.citems").text("");   
        $("#contralist span.citems").append('&nbsp;<a href="javascript:void(0)" onclick="$(this).remove();removeContraList(' +$("#contra_expert").val()+ ')">' +$("#contra_expert").children("[@selected]").text()+ '</a>');
        contraList.push($("#contra_expert").val()); 
        $("#contralist").effect("highlight", {}, 1000);    
    }
}

function removeContraList(id) {
    removeItem(contraList, id);
    eval('$("input[name=contralistval]").val($("input[name=contralistval]").val().replace(/'+id+'/, ""));');
    if($("#contralist span.citems").text() == " ")$("#contralist span.citems").text("");
    if($("input[name=contralistval]").val() == "|")$("input[name=contralistval]").val("");     
}

function newRateSubmit() {

    if(starValidate()) {
        $("input[name=prolistval]").val(proList.join("|")); 
        $("input[name=contralistval]").val(contraList.join("|"));
        $("#extended_searchform").submit();      
    }
    
}

function modRateSubmit(ertid) {

    $("input[name=prolistval]").val($("input[name=prolistval]").val()+"|"+proList.join("|")); 
    $("input[name=contralistval]").val($("input[name=contralistval]").val()+"|"+contraList.join("|"));
    $("#extended_searchform").submit();    
}

function rateIt(eid) {
    $.getJSON("index.php?content=ajax&cmd=isuser", 
        function(data) {
            if(data.success == "true")
                window.location.href = "index.php?content=expert&cmd=rate&id=" +eid;
            else {
                $("#jqDialog").dialog({ 
                    modal: true,
                    title: "Regisztráció szükséges",
                    resizable: false,
                    draggable: false,
                    overlay: { 
                        opacity: 0.5, 
                        background: "black" 
                    },
                    buttons: { 
                        "Ok": function() { 
                            $(this).dialog("close"); 
                        } 
                    } 
                }).html(data.reason);
            }
        $(".ui-dialog-content").css({height:"auto",width:"auto"});
    });
    
}

function showMessageBox(uid) {
    $.getJSON("index.php?content=ajax&cmd=isuser",
        function(data) {
            if(data.success == "true") {
                $.post("index.php?content=ajax&cmd=getmsgbox",
                    {id:uid},
                    function(response) {
                        $("#jqDialog").dialog({ 
                            modal: true,
                            title: "Üzenet küldése",
                            resizable: false,
                            draggable: false,
                            width: 610,
                            height: 300,
                            overlay: { 
                                opacity: 0.5, 
                                background: "black" 
                            },
                            buttons: { 
                                "Küldés": function() { 
                                    sendInternalMesage(uid, 0);     
                                },
                                "Bezárás": function() { 
                                    $(this).dialog("close"); 
                                }  
                            } 
                        }).html(response);
                        $(".ui-dialog-content").css({height:"auto",width:"auto"});    
                    }
                );
            } else {
                $("#jqDialog").dialog({ 
                    modal: true,
                    title: "Regisztráció szükséges",
                    resizable: false,
                    draggable: false,
                    overlay: { 
                        opacity: 0.5, 
                        background: "black" 
                    },
                    buttons: { 
                        "Ok": function() { 
                            $(this).dialog("close"); 
                        } 
                    } 
                }).html(data.reason);
                $(".ui-dialog-content").css({height:"auto",width:"auto"});
            }
    });
}

function sendInternalMesage(uid) {
   
    $.ajax({
        type: "POST",
        url: "index.php?content=msg&cmd=sendmsg",
        data: "toid=" +uid+ "&subject=" +$("#targy").val()+ "&msg=" +$("#uzi").val()+ "&replyid=0",
        beforeSend: function() {
            $("#jqDialog").html("<p>Küldés folyamatban...</p>");
        },
        success: function() {
            $("#jqDialog #extended_searchform input, textarea").attr("disabled", "");
            $("#jqDialog").html("<p>Üzenet sikeresen elküldve!</p>");
            $("button:contains('Küldés')").remove();
            refreshMsgData();
        }
    });
    
}

function showMessage(id) {

    $.get("index.php?content=msg&cmd=getmsg&id=" +id,
        function(data) {
            $("#jqDialog").dialog({ 
                modal: true,
                title: "Üzenet adatai",
                resizable: false,
                draggable: false,
                width: 610,
                height: 300,
                overlay: { 
                    opacity: 0.5, 
                    background: "black" 
                },
                buttons: {
                    "Válasz": function() {
                        $("button:contains('Válasz')").hide();
                        $("button:contains('Küldés')").show();
                        $("#targy").val("[RE]: " +$("#targy").val()); 
                        $("#uzi").val("\n-----------------------\nválasz erre:\n" +$("#uzi").val()).attr("disabled", "").focus();                          if($("input[name=switchtype]").val()==0) {
                            var fa = $("#felado").val();
                            $("#felado").val($("#cimzett").val());
                            $("#cimzett").val(fa);
                        }
                    },
                    "Küldés": function() {
                        $.post("index.php?content=msg&cmd=sendmsg", 
                            //$("#jqDialog #extended_searchform").serialize(),
                            { 
                                toid:$("input[name=touid]").val(),
                                subject:$("#targy").val(),
                                msg:$("#uzi").val(),
                                replyid:$("input[name=mid]").val()
                            },
                            function() {
                                $("#jqDialog").html("<p>Üzenet sikeresen elküldve!</p>");
                                $("button:contains('Küldés')").remove();
                                refreshMsgData();
                            }
                        );      
                    }, 
                    "Bezárás": function() { 
                        $(this).dialog("close");
                        refreshMsgData(); 
                    }  
                },
                open: function() {
                    $("button:contains('Küldés')").hide();
                } 
            }).html(data);
            $(".ui-dialog-content").css({height:"auto",width:"auto"});   
        });  
}

function delMsg(id) {

    $("#jqDialog").dialog({ 
        modal: true,
        title: "Törlés megerősítése",
        resizable: false,
        draggable: false,
        overlay: { 
            opacity: 0.5, 
            background: "black" 
        },
        buttons: { 
            "Igen": function() {
                $.post("index.php?content=msg&cmd=delmsg", "id="+id);
                $(this).html("<p>Üzenet törlése sikeresen megtörtént!</p>");
                $("button:contains('Igen')").remove();
                $("button:contains('Nem')").text("Bezárás");
                refreshMsgData();    
            },
            "Nem": function() {
                $(this).dialog("close");    
            }
        }    
    }).html("<p>Biztos benne, hogy törli ezt az üzenetet?</p>");
    $(".ui-dialog-content").css({height:"auto",width:"auto"});
}

function refreshMsgData() {
    $.post("index.php?content=msg&cmd=getmessages",
        function(response) {
            $("#msgtable_box").html(response);
            $("#footer").css("top", $(document).height());
        }
    );
}

function orderList(type, page, max, orient) {
    $.post("index.php?content=ajax&cmd=orderes",
        { otype:type, opage:page, omax:max, oorient:orient },
        function(response) {
            $(".paginate").remove();
            $(".box_center:eq(2)").html(response);
            $("#footer").css("top", $(document).height());
        }
    );
}

function modifyRate(eid) {
    $.getJSON("index.php?content=ajax&cmd=israted&id="+eid, 
        function(data) {
            if(data.success == "true")
                window.location.href = "index.php?content=expert&cmd=modrate&id=" +eid;
            else {
                $("#jqDialog").dialog({ 
                    modal: true,
                    title: "Értékelés nem módosítható",
                    resizable: false,
                    draggable: false,
                    width: 350,
                    overlay: { 
                        opacity: 0.5, 
                        background: "black" 
                    },
                    buttons: { 
                        "Ok": function() { 
                            $(this).dialog("close"); 
                        } 
                    } 
                }).html(data.reason);
                $(".ui-dialog-content").css({height:"auto",width:"auto"});
            }
    });
}

function yearFilter() {
    $.post("index.php?cmd=filter",
        {year:$("select[name=yearfilter]").val()},
        function() {
            window.location.reload();
        }
    );
}

function monthFilter() {
    $.post("index.php?cmd=filter",
        {month:$("select[name=monthfilter]").val()},
        function() {
            window.location.reload();
        }
    );
}

function sendEnter(evt, code) {
    evt = (evt) ? evt : event;
    var charCode = (evt.charCode) ? evt.charCode :
        ((evt.which) ? evt.which : evt.keyCode);
    if (charCode == 13 || charCode == 3) {
        eval(code);
        return true;
    } else {
        return false;
    }
}

function starValidate() {
    if($(".starsi img[src=images/star_on.png]").length == 0) {
        $("#jqDialog").dialog({ 
            modal: true,
            title: "Értékelés szükséges",
            resizable: false,
            draggable: false,
            overlay: { 
                opacity: 0.5, 
                background: "black" 
            },
            buttons: { 
                "Ok": function() {
                    $(this).dialog("close");  
                }
            }    
        }).html("<p>Nem adott meg csillagokat (1-5-ig)!</p>");
        return false;
    } else {
        return true;    
    }
}