/* Author: Dawid Lizak

*/

var ieVersion = $.browser.msie ? parseInt($.browser.version, 10) : undefined;

// Carousels
if ($("#prev-editions").length) {
    $("#prev-editions").carouFredSel({
        items: 1,
        scroll: {
            items: 1,
            pauseOnHover: true
        },
        auto: {
            pauseDuration: 5000
        },
        pagination: {
            container: "#prev-editions-pagination",
            pauseOnHover: true
        }
    });
}

if ($("#speakers-list ul").length) {
    $("#speakers-list ul:first").carouFredSel({
        items: 2,
        scroll: {
            items: 2,
            pauseOnHover: true
        },
        auto: {
            pauseDuration: 3000
        }
    });
}

if ($("#movies-list ul").length) {
    $("#movies-list ul:first").carouFredSel({
        items: 1,
        scroll: {
            items: 1
        },
        auto: {
            play: false
        },
        pagination: {
            container: "#movies-list-pagination"
        },
        prev: {
            button: "#movies-list .prev"
        },
        next: {
            button: "#movies-list .next"
        },
        scroll: {
            onAfter: function() {
                $(this).find("object").parent().flowplayer().each(function() {
                    this.unload();
                });
            }
        }
    });
}

if ($(".partners ul").length) {
    $(".partners ul").not(".partners-single ul").carouFredSel({
        items: 2,
        scroll: {
            items: 2
        },
        auto: {
            pauseDuration: 3000
        }
    });
}


// Contact Tabs
if ($("#side-contact")) {
    $("#side-contact").tabs();
}


// movies-list
$('#movies-list ul a').flowplayer("flash/flowplayer-3.2.7.swf", {
    plugins: {
        controls: {
            all: false,
            scrubber: true,
            mute: true,
            height: 25,
            autoHide: false
        }
    }
});


// Google & Facebook boxes
$("#google-box").hover(function() {
    $(this).stop(true, false).animate({right: "0"});
    }, function() {
    $(this).stop(true, false).animate({right: "-314px"});
});

$("#facebook-box").hover(function() {
    $(this).stop(true, false).animate({right: "0"});
    }, function() {
    $(this).stop(true, false).animate({right: "-306px"});
});


// Uniform
if (ieVersion <= 7) {
    $("input:checkbox, input:radio").uniform();
}
else {
    $("select, input:checkbox, input:radio").uniform();
}


// registration-form
if ($("#registration-form").length) {
    $("#registration-form input[name='select_form_type']").on("click", function(e) {
        var $that = $(this);
        var $registrationForm = $("#registration-form");
        
        if($that.attr("id") === "select-form-type-long" && $that.is(":checked")) {
            $(".long").show();
            
            var $reqElements = $registrationForm.find("textarea[id^='speaker_note_']");
            $reqElements.addClass("required").after(' <em class="req">*</em>');
        }
        else {
            $(".long").hide();
            var $reqElements = $registrationForm.find("textarea[id^='speaker_note_']");
            $reqElements.removeClass("required").next('em.req').remove();
        }
    });
    
    $(".registration-form-add a").on("click", function(e) {
        e.preventDefault();
        
        var $speakerTbl = $(this).closest("table").prev();
        var $newSpeakerTbl = $speakerTbl.clone();
        var id = $newSpeakerTbl.find("[name]:first").attr("name").match(/\[(\d+)\]$/)[1];
        
        var $labels = $newSpeakerTbl.find("[for$='"+ id +"']");
        var $inputs = $newSpeakerTbl.find("[id$='"+ id +"']");
        
        $newSpeakerTbl.find('label[generated="true"]').remove();
        
        $labels.each(function(i, val) {
            var $label = $(this);
            var newId = id*1+1;
            var newForValue = $label.attr("for").replace(/\d+$/, newId);
            $label.attr("for", newForValue);
        });
        
        $inputs.each(function(i, val) {
            var $input = $(this);
            var newId = id*1+1;
            var newIdValue = this.id.replace(/\d+$/, newId);
            var newNameValue = $input.attr("name").replace(/\[(\d+)\]$/, "["+ newId +"]");
            $input.attr("name", newNameValue)
                  .removeClass("error")
                  .val("");
            
            this.id = newIdValue;
        });
        
        $speakerTbl.after($newSpeakerTbl);
    });
}


// attendee-reg-form
if ($("#attendee-reg-form").length) {
    $("#attendee-reg-form").show();
    $(".attendee-reg-form-nojs").hide();
    
    var getAttendeePrices = function() {
        $.ajax({
            type: "POST",
            url: "/ajax/discount",
            data: $("#attendee-reg-form").serialize(),
            dataType: "json",
            success: function(data) {
                $("#attendee-reg-form-attendees").find("fieldset").each(function() {
                    $that = $(this);
                    
                    var eventId = $that.find("dl.attendee-person-dl-event input:checked").val();
                    var $valueDl = $that.find("dl.attendee-person-dl-value");
                    
                    var singlePrice = data[eventId].price;
                    
                    if ($valueDl.length != 0) {
                        $valueDl.find("span.attendee-person-price").html(singlePrice);
                    }
                    else {
                        $that.append('<dl class="attendee-person-dl-value">'+
                                     '    <dt>Wartość zamówienia:</dt>'+
                                     '    <dd><span class="attendee-person-price">'+ singlePrice +'</span> zł</dd>'+
                                     '</dl>');
                    }
                });
                
                $("#attendee-reg-price-all").html(data.price_all);
                $("#attendee-reg-price-discount-all").html(data.price_discount_all);
                $("#attendee-reg-discount-code").html(data.price_discount);
                $("#attendee-reg-price-final").html(data.price_final);
                $("#attendee-reg-price-final-b").html(data.price_final_b);
                
                
                if ($("#code").val() && !data.price_discount) {
                    $("#attendee-reg-discount-msg").html("Wpisany kod jest nieprawidłowy.<br>Prosimy skontaktować się z handlowcem tel. 22 314 14 30 ");
                }
                else {
                    $("#attendee-reg-discount-msg").html("");
                }
            }
        });
    }
    
    
    $("#attendee-person-add").on("click", function(e) {
        e.preventDefault();
        
        var $person = $(this).prev("dl");
        var $newPerson = $person.clone().show();
        var newId = parseInt($person.find("input:first").attr("name").match(/^users\[(\d+)\].*?$/)[1], 10) + 1;
        
        var reId = /^users\-\d+\-(.*?)$/;
        var reUniformId = /^uniform\-users\-\d+\-(.*?)$/;
        var reName = /^users\[\d+\](.*?)$/;
        
        var eventRadioCount = 0;
        
        $newPerson.find("*").each(function(i, val) {
            var $that = $(this);
            
            if (this.id) {
                var newAttrId;
                
                if (this.id.search(reId) != -1) {
                    newAttrId = this.id.replace(reId, "users-"+ newId +"-$1");
                    this.id = newAttrId;
                }
                if (this.id.search(reUniformId) != -1) {
                    newAttrId = this.id.replace(reUniformId, "uniform-users-"+ newId +"-$1");
                    this.id = newAttrId;
                }
                if (this.id.search(/^users\-\d+\-phone$/) != -1) {
                    $that.removeClass("required error");
                }
            }
            if (this.name) {
                var newAttrName = this.name.replace(reName, "users["+ newId +"]$1");
                this.name = newAttrName;
            }
            if (this.getAttribute("for")) {
                this.setAttribute("for", this.getAttribute("for").replace(reId, "users-"+ newId +"-$1"));
            }
            if (this.getAttribute("htmlFor")) {
                this.setAttribute("htmlFor", this.getAttribute("htmlFor").replace(reId, "users-"+ newId +"-$1"));
            }
            if (this.disabled) {
                this.disabled = false;
            }
            
            if (this.nodeName == "INPUT") {
                if (this.type == "text") {
                    $that.val("");
                    $that.removeClass("error");
                }
                if (this.type == "checkbox") {
                    $that.attr("checked", false);
                    $that.unwrap().unwrap().uniform();
                }
                if (this.type == "radio") {
                    var $radio = $('<input type="radio" name="users['+ newId +'][event]" id="users-'+ newId +'-event-'+ ++eventRadioCount +'" value="'+ eventRadioCount +'">');
                    $that.unwrap().unwrap().replaceWith($radio);
                    $radio.uniform();
                }
            }
            if (this.nodeName == "SELECT") {
                if (!(ieVersion && ieVersion <= 7)) {
                    $that.prev().remove();
                    $that.unwrap().uniform();
                }
                else {
                    $that.css("visibility", "hidden");
                }
            }
            if (this.getAttribute("generated") ||
                this.className == "attendee-person-dl-value") {
                $that.remove();
            }
        });
        
        var $newPersonFirstDt = $newPerson.find("dt").first();
        if ($newPersonFirstDt.contents("img").length == 0) {
            $newPersonFirstDt.append('<img src="img/t.gif" class="attendee-person-remove">');
        }
        
        $person.after($newPerson);
        
        $.uniform.update(
            $newPerson.find("dl.attendee-person-dl-event label:first-child input")
                      .attr("checked", "checked")
        );
        
        getAttendeePrices();
    });
    
    
    $(".attendee-person-dl-event input").live("change", function() {
        $that = $(this);
        
        if (ieVersion && ieVersion <= 7) {
            var $eventSelect = $that.closest("dl").parent().find(".attendee-person-dl-theme select");
        }
        else {
            var $eventSelect = $that.closest("dl").parent().find(".attendee-person-dl-theme .selector");
        }
        
        if ($that.val() == 2 || $that.val() == 3) {
            $eventSelect.css("visibility", "visible");
        }
        else {
            $eventSelect.css("visibility", "hidden");
        }
        
        getAttendeePrices();
        $that.blur();
    });
    
    $("#attendee-person-add").trigger("click");
    
    
    // linkowanie inputów pierwszego uczestnika
    var $attendeePersonal = $("#attendee-reg-form-personal");
    var $attendeePersonalInputs = $("#firstname, #lastname, #position, #mail, #phone", $attendeePersonal);
    
    var $attendeeFirst = $("#attendee-reg-form-attendees dl:eq(0)");
    var $attendeeFirstInputs = $(".attendee-person-dl-field-inline input, .attendee-person-dl-field-phone-input input", $attendeeFirst);
    
    $attendeeFirst.hide();
    $attendeeFirstInputs.attr("disabled", "disabled");
    
    $attendeePersonalInputs.each(function(i, val) {
        $(this).on("change", function(e) {
            $($attendeeFirstInputs[i]).val($(this).val());
        });
    });
    
    $("#attendee-reg-form-personal #participant").live("change", function() {
        if ($(this).is(":checked")) {
            $attendeeFirst.show();
            var $lastPersonDl = $(".attendee-person-dl:last");
            var $inputs = $(".attendee-person-dl-field-inline input", $lastPersonDl);
            
            if (!$inputs[0].value && !$inputs[1].value && !$inputs[2].value && !$inputs[3].value) {
                $lastPersonDl.find(".attendee-person-remove").trigger("click");
            }
        }
        else {
            $attendeeFirst.hide();
        }
        getAttendeePrices();
    });
    
    $("#attendee-reg-form-invoice #consulting").live("change", function() {
        getAttendeePrices();
    });
    
    $(".attendee-person-dl-field-phone input").live("change", function() {
        var $this = $(this);
        var $relatedInput = $this.closest("dl").next(".attendee-person-dl-field-phone-input").find("input");
        
        if ($this.is(":checked")) {
            $relatedInput.addClass("required");
        }
        else {
            $relatedInput.removeClass("required error");
            $relatedInput.next("label.error").remove();
        }
    });
    
    
    // dodawanie przycisków do usuwania uczestników
    $(".attendee-person-remove").live("click", function() {
        $(this).closest("dl").remove();
        getAttendeePrices();
    });
    
    
    var codeTimeout;
    $("#code").on("keyup", function() {
        if (codeTimeout) {
            clearTimeout(codeTimeout);
        }
        
        codeTimeout = window.setTimeout(function() {
            getAttendeePrices();
        }, 200);
    });
}


// form validation
$.validator.addMethod("emailunique", function(value, element) {
    var result;
    var userFullId;
    var userId;
    
    if (element.id == "mail") {
        userFullId = "users-0-mail";
        userId = 0;
    }
    else {
        userFullId = element.id;
        userId = element.id.match(/^users-(\d+)-mail$/)[1];
    }
    
    $.ajax({
        type: "POST",
        url: "/ajax/check-email",
        data: $("#attendee-reg-form").serialize() +"&users%5B"+ userId +"%5D%5Bmail%5D="+ value +"&users%5B"+ userId +"%5D%5Bcurrent%5D=1",
        dataType: "json",
        async: false,
        success: function(data) {
            result = !data[userFullId];
        }
    });
    
    return result;
}, "Email powtarza się lub istnieje już w bazie");


$.validator.addMethod("min800-max1000", function(value, element) {
    var valLen = $(element).val().length;
    return valLen >= 800 && valLen <= 1000;
}, "Liczba znaków musi zawierać się między 800 a 1000");


$.validator.addMethod("max1000", function(value, element) {
    var valLen = $(element).val().length;
    return valLen <= 1000;
}, "Maksymalnie 1000 znaków");


$.validator.addMethod("max600", function(value, element) {
    var valLen = $(element).val().length;
    return valLen <= 600;
}, "Maksymalnie 600 znaków");


$.extend($.validator.messages, {
    required: "To pole jest wymagane",
    email: "Proszę wprowadzić poprawny email"
});


$("#attendee-reg-form").validate();
$("#registration-form").validate();

$("#commentform").validate();
$("#newsletter").validate();
$("#contact1").validate();
$("#contact2").validate();
$("#contact3").validate();


$("#registration-form-success").dialog({
    "modal": true,
    "autoOpen": true,
    "buttons": {
        "ok": {
            "text": "OK",
            "class": "btn btn-small btn-type1",
            "click": function() {
                $(this).dialog("close");
            }
        }
    }
});

$("#registration-form-success").dialog({
    "modal": true,
    "autoOpen": true,
    "buttons": {
        "ok": {
            "text": "OK",
            "class": "btn btn-type2 btn-small",
            "click": function() {
                $(this).dialog("close");
            }
        }
    }
});
