﻿///<reference path="../inc/jquery.intellisense.js"/>

//returns array of queryString parameters
//USAGE:
//var qs_params = new Array();
//qs_params = get_querystring_params();
function get_querystring_params() 
{
    var qsParm = new Array();
    var query = window.location.search.substring(1);
    var parms = query.split('&');
    for (var i=0; i<parms.length; i++) 
    {
        var pos = parms[i].indexOf('=');
        if (pos > 0) 
        {
            var key = parms[i].substring(0,pos);
            var val = parms[i].substring(pos+1);
            qsParm[key] = val;
        }
    }
    return qsParm;
}


jQuery.fn.centerInClient = function(options) {
    /// <summary>Centers the selected items in the browser window. Takes into account scroll position.
    /// Ideally the selected set should only match a single element.
    /// </summary>    
    /// <param name="fn" type="Function">Optional function called when centering is complete. Passed DOM element as parameter</param>    
    /// <param name="forceAbsolute" type="Boolean">if true forces the element to be removed from the document flow 
    ///  and attached to the body element to ensure proper absolute positioning. 
    /// Be aware that this may cause ID hierachy for CSS styles to be affected.
    /// </param>
    /// <returns type="jQuery" />
    var opt = { forceAbsolute: false,
        container: window,    // selector of element to center in
        completeHandler: null
    };
    $.extend(opt, options);

    return this.each(function(i) {
        var el = $(this);
        var jWin = $(opt.container);
        var isWin = opt.container == window;

        // force to the top of document to ENSURE that 
        // document absolute positioning is available
        if (opt.forceAbsolute) {
            if (isWin)
                el.remove().appendTo("body");
            else
                el.remove().appendTo(jWin.get(0));
        }

        // have to make absolute
        el.css("position", "absolute");

        // height is off a bit so fudge it
        var heightFudge = isWin ? 2.0 : 1.8;

        var x = (isWin ? jWin.width() : jWin.outerWidth()) / 2 - el.outerWidth() / 2;
        var y = (isWin ? jWin.height() : jWin.outerHeight()) / heightFudge - el.outerHeight() / 2;

        el.css("left", x + jWin.scrollLeft());
        el.css("top", y + jWin.scrollTop());

        // if specified make callback and pass element
        if (opt.completeHandler)
            opt.completeHandler(this);
    });
}

//function display message in blank texbox (from title), and clears it when focused
jQuery.fn.hint = function() {
    return this.each(function() {
        
        var t = jQuery(this); // get jQuery version of 'this'
        var title = t.attr('title');// get it once since it won't change
        // only apply logic if the element has the attribute
        if (title) {
            t.blur(function() {// on blur, set value to title attr if text is blank
                if (t.val() == '') {
                    t.val(title);
                    t.addClass('blur');
                }
            });
            // on focus, set value to blank if current value 
            // matches title attr
            t.focus(function() {
                if (t.val() == title) {
                    t.val('');
                    t.removeClass('blur');
                }
            });
            // clear the pre-defined text when form is submitted
            t.parents('form:first()').submit(function() {
                if (t.val() == title) {
                    t.val('');
                    t.removeClass('blur');
                }
            });
            // now change all inputs to title
            t.blur();
        }
    });
}

function show_hide_element(selector) {
    $(selector).slideToggle();
}

//  0  |  1 |    2   |  3    |    4     |    5  |        6                      |
//paket|cena|kolicina|popust%|aktivacija|popust%|dodatne stroritve              |
//m1   | 19 |   6    |  10   |   79     |  50   |320;1;0#810;1;0#30;1;0#320;1;0 |
var bill_data = ["-1", "-1", "-1", "-1", "-1", "-1", "-1"];

var packet_selected = false;
var user_valid = false;
var is_old_user = "NE";
var checkboxes_dodatne;

jQuery(document).ready(function() {


    //select checkbox if querystring parameter is present

    var qs_params = new Array();
    qs_params = get_querystring_params();
    if (qs_params["packet"] != null) { //npr: m2
        var ltr = qs_params["packet"].substr(0, 1);
        var num = qs_params["packet"].substr(1, 1);

        var checkbox = $("input#chk_" + ltr + "_" + num);

        clear_checkboxes(checkbox.attr("id"));
        checkbox.attr("checked", "checked");
        //calc_price(); //chk_group_m2

    }

    // ----- STEP 1 ---------------------
    //----------------------------------

    var div_yes = $("DIV#is_user_yes");
    var div_no = $("DIV#is_user_no");
    is_old_user = $("INPUT[name$=rbl_is_user]:checked").val();
    if (is_old_user == "DA") {
        bill_data[4] = "0";
        div_yes.slideDown();
        div_no.slideUp();

    }
    if (is_old_user == "NE") {
        bill_data[4] = "79";
        div_yes.slideUp();
        div_no.slideDown();

    }

    //radiobutton DA, NE clicked
    $("INPUT[name$=rbl_is_user]").click(function(e) {
        if ($(this).val() == "DA") {
            is_old_user = "DA";
            bill_data[4] = "0";
            div_yes.slideDown();
            div_no.slideUp();

        }
        else {
            is_old_user = "NE";
            bill_data[4] = "79";
            div_yes.slideUp();
            div_no.slideDown();
            //validate form to show *
            Page_ClientValidate("validation_step1_u_new");
        }
        calc_price();

    });

    //---- username, password inputs
    var tbx_user = $("INPUT[name$=tbx_username]");
    var tbx_pass = $("INPUT[name$=tbx_password]");
    tbx_user.hint();
    //check username and password
    tbx_user.blur(function() {

        if (tbx_pass.val() != "") {
            //var pass = $(this);
            check_user();
        }
    });
    tbx_pass.blur(function() {

        //var pass = $(this);
        check_user();
    });
    //----

    //select packet checkbox clicked
    $(".narocilo_cenik INPUT:checkbox").click(function() {

        var chk = $(this);

        //first clear all checked
        clear_checkboxes(chk.attr("id"));
        calc_price(); //chk_group_m2

    });

    //selected packet M ddl value changed ---- M
    $("DIV#m_additional_packet_options SELECT#ddl_months_m").change(function() {
        calc_price();

    });

    //selected packet P textbox value changed ---- P
    $("DIV#p_additional_packet_options INPUT#tbx_kol_p").keyup(function() {
        var tbx = $(this);
        //only values 1-99 allowed
        if (tbx.val() != parseInt(tbx.val())) { //check if string is numeric
            if (tbx.val() != "") { tbx.val("1"); } //we set value to 1 if not empty textbox
        }
        else { //if numeric, check if in range 1-99
            if (parseInt(tbx.val()) < 1 || parseInt(tbx.val()) > 99) {
                tbx.val("1");
            }
        }

        calc_price();
    });
    $("DIV#p_additional_packet_options INPUT#tbx_kol_p").blur(function() {
        var tbx = $(this);
        if (tbx.val() == "") { tbx.val("1"); } //if user left blank texbox, we take default value 1 and calculete prices
        calc_price();
    });

    //selected packet C textbox value changed ---- C
    $("INPUT#tbx_nomails_c_1").keyup(function() {
        calc_price();
    });
    $("INPUT#tbx_nomails_c_1").blur(function() {
        var tbx = $(this);
        var ok = true;
        //only values from 50001 allowed
        if (tbx.val() != parseInt(tbx.val())) { //check if string is numeric
            tbx.val("50001");
            ok = false;
        }
        else { //if numeric, check if in range 1-99
            if (parseInt(tbx.val()) < 50001) {
                tbx.val("50001");
                ok = false;
            }
        }

        if (ok == false) { alert("Dovoljene so samo numerične vrednosti od 50001 naprej."); }
        calc_price();
    });

    $("#a_step1_next").click(function() {
        //alert("naslednji tab");
        alert(validate());
    });

    //DODATNE STORITVE
    checkboxes_dodatne = $("DIV#dodatne_checkboxes INPUT:checkbox");
    $("#dodatne_storitve_link").click(function() {
        //step1_frame3

        var some_checked = false;

        checkboxes_dodatne.each(function() {
            var chk = $(this);
            if (chk.attr("checked") == true) { //find the checked one
                some_checked = true;
            }
        });

        if (some_checked == false) {
            $("DIV#step1_frame3").slideToggle();
        }

    });

    checkboxes_dodatne.click(function() {
        calc_price();

    });



    $("DIV#packet_switch_links").click(function() {

        $("DIV#c_packet_container").slideToggle();

    });

    calc_price();  //on start calculate price (in case if something is already checked)
    // -----END STEP 1 ---------------------


    // ----- STEP 2 ---------------------
    //----------------------------------

    //davcni zavezanec checkbox
    $("INPUT[id$=chk_zavezanec]").click(function() {
        $("SPAN#si_tax_number").toggleClass("hide");

    });

    // ----- STEP 3 ---------------------
    //----------------------------------
    

});


// ----- STEP 1 ---------------------
//----------------------------------
function check_user() {
    
    var step1_btn = $("#btn_step1_next_new_user_wrapper");
    var img_loading_btn = $("IMG[id$=img_ajax_loading_btn]");
    step1_btn.hide();
    img_loading_btn.show();
    
    //var pass = $(this);
    var pass_field = $("INPUT[name$=tbx_password]");
    var user = $("INPUT[name$=tbx_username]");
    var data_div = $("DIV#user_data_display");
    var img_yes = $("IMG[id$=user_yes]");
    var img_no = $("IMG[id$=user_no]");
    var img_loading = $("IMG[id$=img_ajax_loading]");

    img_no.hide();
    img_yes.hide();
    img_loading.show();
    //data_div.html("<br /><IMG src=\"../images/ajax_loading_small.gif\" alt=\"Nalagam...\" />");

    //var get_url = "http://to.mato.si/tomato/form.php?form=6";
    //var get_url = "tomato/form.php?form=6";

    $.ajax({
        type: "GET",
        url: "../inc/ajax_calls.aspx?action=check_user&username=" + user.val() + "&password=" + pass_field.val(),
        data: "",
        beforeSend: function() { },
        error: function(error) {
            img_no.show();
            img_yes.hide();
            img_loading.hide();
            data_div.html("");
            user_valid = false;
            $("SPAN[id$=rbl_is_user]").children().next().nextAll().fadeIn();
        },
        success: function(response) {

            if (response == "0") {
                img_no.show();
                img_yes.hide();
                img_loading.hide();
                data_div.html("");
                user_valid = false;
                $("SPAN[id$=rbl_is_user]").children().next().nextAll().fadeIn();

            }
            else if (response == "1") { //if username and password match
                user_valid = true;
                img_no.hide();
                img_yes.show();
                //hide new user radio button option
                $("SPAN[id$=rbl_is_user]").children().next().nextAll().fadeOut();
                //load user/company data
                $.get("../inc/ajax_calls.aspx?action=get_user_data_html&username=" + user.val(), function(data) {

                    var data_array = data.split('|');
                    data_div.hide();
                    data_div.html(data_array[0]);
                    data_div.slideDown();
                    img_loading.hide();

                    var tbx_id_user = $("INPUT[id$=tbx_hidden_id_user]").val(data_array[1]);
                });



            }
            else {
                user_valid = false;
                alert("Error: " + response);
            }
            step1_btn.show();
            img_loading_btn.hide();
        }

    });             //end ajax
} // END function check_user() {


//clears checkboxes, except the exception one.
function clear_checkboxes(exception_checkbox_id) {
    $(".narocilo_cenik INPUT:checkbox").each(function() {
        if (exception_checkbox_id != $(this).attr("id")) {
            this.checked = "";
        }
        else {
            this.checked = "checked";
        }
    });
    
    /* hide
    $(".narocilo_cenik SELECT[id^=ddl_m_]").each(function() {
        $(this).hide();
    });
    $(".narocilo_cenik INPUT[id^=tbx_p_]").each(function() {
        $(this).hide();
    });*/
}
//clears the green boxes around prices, and prices
/*function clear_prices() {
    $(".narocilo_cenik SPAN[id^=price_total_]").each(function() {
        $(this).removeClass("box_orange");
        $(this).html("0");
    });

    
}*/


//---- calculates and sets the prices an sets some styles ....
function calc_price() {
    packet_selected = false;
    $(".narocilo_cenik INPUT:checkbox").each(function() { //GO thrue checkboxes

        var chk = $(this);
        if (chk.attr("checked") == true) { //find the checked one
            //alert(chk.attr("id"));
            packet_selected = true;
            //alert("checked found 1: " + packet_selected);

            group = chk.attr("name");
            var grp_letter = group.substr(group.length - 2, 1);
            var grp_num = group.substr(group.length - 1, 1);
            //alert(grp_letter+grp_num);


            bill_data[0] = grp_letter + grp_num;
            bill_data[3] = "0"; //popust za paket je 0%
            bill_data[5] = "0"; //popust za paket je 0%


            var total_price = "0";
            var data_array = new Array();
            data_array = "0|0|0";
            //get some packet data (from hidden field)
            data_array = $("SPAN#" + grp_letter + "_total_" + grp_num).html().split('|'); //1500|19|0,0126
            bill_data[1] = data_array[1];

            //za dodatne storitve---
            var chk_dodatno_3 = $("INPUT[id$=chk_dodatno_3]"); //pri dodatnih opcijah checkbox za tel.podporo
            chk_dodatno_3.attr("disabled", "disabled");
            //------------------------

            //-- prikazi dodatne moznosti za izbran paket (skrij za ostale pakete)
            $("DIV[id$=_additional_packet_options]").each(function() {
                if ($(this).attr("id").substr(0, 1) != grp_letter) { $(this).slideUp(); }
            });
            var packet_options_div = $("DIV#" + grp_letter + "_additional_packet_options");
            packet_options_div.slideDown();

            var span_total_price_c1 = $("SPAN#price_total_c1"); //packet C total price
            span_total_price_c1.removeClass("box_orange");
            //-------------
            //--- M ----------------------------------------------------
            if (grp_letter == "m") { //M paketi

                /*var ddl = $("SELECT#ddl_m_" + grp_num); //ddl_m_2
                ddl.show();
                bill_data[2] = ddl.val();*/

                var ddl_months = $("SELECT#ddl_months_m");
                bill_data[2] = ddl_months.val();
                //nastavimo popust za pakete
                if (ddl_months.val() == "6") { bill_data[3] = "10"; bill_data[5] = "50"; }
                if (ddl_months.val() == "12") { bill_data[3] = "15"; bill_data[5] = "80"; }

                //ce je m paket lahko omogocimo checkbox dodatno storitev telefonsko podporo
                chk_dodatno_3.removeAttr("disabled");

            }
            else if (grp_letter == "p") { //P paketi//--- P -------------------------------------

                var tbx = $("INPUT#tbx_kol_p"); //tbx_p_2
                bill_data[2] = tbx.val();
                bill_data[3] = "0";
                bill_data[5] = "0";

                chk_dodatno_3.removeAttr("checked");

            }
            else if (grp_letter == "c") { //C paketi//--- C ----------------------------------------------------

                var no_mails_tbx = $("INPUT#tbx_nomails_c_1");
                //calculate price
                var price_per_mail_span = $("SPAN#price_permail_c_1");
                var price_per_mail = 0.0098;

                if (no_mails_tbx.val() < 100000) { price_per_mail = 0.0098; }
                else { price_per_mail = 0.0088; }

                //alert(parseInt(no_mails));

                price_per_mail_span.html(price_per_mail);

                bill_data[1] = price_per_mail;
                bill_data[2] = no_mails_tbx.val(); //-quantity
                bill_data[3] = "0";
                bill_data[5] = "0";


                span_total_price_c1.html(round_number(price_per_mail * no_mails_tbx.val(), 3));
                span_total_price_c1.addClass("box_orange");

                chk_dodatno_3.removeAttr("checked");
            }

            total_price = bill_data[1] * bill_data[2]; //bill_data[1] = price; bill_data[2]= quantity

            //-----set additioanl packet options price data-------
            var span_price_total = $("SPAN#price_total_" + grp_letter);
            var total_price_discount = (total_price * bill_data[3]) / 100;
            span_price_total.html(total_price - total_price_discount);  //

            var price_dics_act = (79 * bill_data[5]) / 100;
            $("SPAN#price_total_act").html(round_number(79 - price_dics_act, 3));

            if (grp_letter == "m") { //------ M
                if (bill_data[3] != "0") {
                    $("SPAN#price_total_m_notes").html(
                        "&nbsp;&nbsp;" + display_dicsount_old_price(total_price) + display_discount_percent(bill_data[3])
                    );

                }
                else { $("SPAN#price_total_m_notes").html(""); }

                //set activation price discount
                if (bill_data[5] != "0") {
                    $("SPAN#price_total_act_notes").html(
                        "&nbsp;&nbsp;" + display_dicsount_old_price(79) + display_discount_percent(bill_data[5])
                    );
                }
                else { $("SPAN#price_total_act_notes").html(""); }
            }
            else { //if not M ... activation price has no discount
                $("SPAN#price_total_act_notes").html("");
            }
            if (grp_letter == "p") {//------ P
                $("SPAN#price_total_p_notes").html(
                    "&nbsp;&nbsp;( Št. email sporočil: " + bill_data[2] * data_array[0] + " )"
                );
            }
            if (grp_letter == "c") {//------ C

            }

            //------------------------------


            //set povzetek data
            var selected_val = $("INPUT[name$=rbl_is_user]:checked").val();
            if (selected_val == "NE") {
                $("SPAN#summary_activation_price").html("79 €");
                $("SPAN#summary_packet_price").html(round_number(total_price, 3) + " €");
                var sum_price = total_price + 79;
                $("SPAN#summary_total").html(round_number(sum_price, 3) + " €");

            }
            else {
                $("SPAN#summary_activation_price").html("0 €");
                $("SPAN#summary_packet_price").html(round_number(total_price, 3) + " €");
                $("SPAN#summary_total").html(round_number(total_price, 3) + " €");
            }

            //v ceni upostevamo se dodatne storitve
            poracunaj_dodatne_storitve(grp_letter, grp_num);

            //save data to hidden input data
            set_hidden_bill_sum_data();

        }
        if (packet_selected == true) {//if we found checked, we can step out of the loop
            return false; //to step out of the jQuery loop
        }

    });                          //END .each(function() { //GO thrue checkboxes

    
    
    //alert("checked found 2: " + packet_selected);
    if (packet_selected == true) {

        //clear_prices();
    }
    //alert(group + ",  " + grp_letter + ", " + grp_num);
} //END function calc_price()



function poracunaj_dodatne_storitve(grp_letter, grp_num) {

    var data_6 = "";
    var some_checked = false;
    var notes = $("SPAN#dodatno_3_price_notes");
    notes.html("");
    //loop skozi checkboxe
    var count = 0;
    checkboxes_dodatne.each(function() {
        //bill_data
        //|        6                      |
        //|dodatne stroritve              |
        //|320;1;0#810;1;0#30;1;0#320;1;0 |

        var chk = $(this);
        var chk_id = chk.attr("id") //npr: ctl00_content_1_chk_dodatno_3
        var storitev_num = "1";
        storitev_num = chk_id.substr(chk_id.length - 1, 1); //npr 3

        var price = $("span#dodatno_" + storitev_num + "_price"); //npr: dodatno_3_price"
        
        if (chk.attr("checked") == true) { //poiscemo obkljukane
            some_checked = true;
            data_6 += "!" + $.trim(price.html()) + ";";  //cena

            price.addClass("box_orange");
            
            //if tel. support --- for packets M
            if (count == 2) {
                var ddl_months = $("SELECT#ddl_months_m OPTION:selected");
                data_6 += ddl_months.val() + ";" + ddl_months.attr("title");

                if (ddl_months.val() != "1") {

                    var price_no_discount = ddl_months.val() * $.trim(price.html())
                    var price_with_discount = price_no_discount - ((price_no_discount * ddl_months.attr("title")) / 100);

                    notes.html(
                        "<span class=\"box_orange\">Cena: " + price_with_discount + " €</span> " +
                        display_dicsount_old_price(price_no_discount) + " " +
                        display_discount_percent(ddl_months.attr("title"))
                    );
                    price.removeClass("box_orange");

                }

            }
            else {
                data_6 += "1;0";

            }
            
            
        }
        else {
            data_6 += "!0;0;0";
            price.removeClass("box_orange");
        }

        if (some_checked == true) { //ce ja kateri obkljukan je okvir avtomatično prikazan
            $("DIV#step1_frame3").show();
        }
        count++;
    });

    data_6 = data_6.substring(1);
    
    bill_data[6] = data_6;

}

function set_hidden_bill_sum_data()
{
    var tmp_data = "";
    for(var i=0; i<bill_data.length; i++)
    {
        if(i==0) { tmp_data = tmp_data + bill_data[i]; }
        else { tmp_data = tmp_data + "|" +bill_data[i]; }
    }
    $("INPUT[id$=data_selected_packet]").val(tmp_data);
}

//------ STEP 1 NEXT CLICK ---------------
function on_btn_step1_next_click() {
    
    var all_valid = false;
    
    if (is_old_user == "DA") { //user enters username and pass
        if (user_valid == true) {
            all_valid = true;
        }
    }
    if (is_old_user == "NE") { //new user - fills the new user form

        if (Page_ClientValidate("validation_step1_u_new")) {

            all_valid = true;
        }
    }
    
    if (packet_selected == false) {
        all_valid = false;
    }

    //all_valid = true; //za testiranje!!!
    if (all_valid == true) {

        var tab_strip = $find("ctl00_content_1_steps_tabs");

        var tabs = tab_strip.get_allTabs();
        tabs[1].enable();
        tabs[1].select();
        //return false;
        //return Page_IsValid;
    }
    else {
        alert("Prosimo pravilno izpolnite vsa zahtevana polja \n in izberite paket.");
        var tab_strip = $find("ctl00_content_1_steps_tabs");

        var tabs = tab_strip.get_allTabs();
        tabs[1].disable();
        tabs[2].disable();
        tabs[3].disable();
        
    }


}

function display_discount_percent(discount) {
    return "<SPAN style=\"color:red;\">Popust: <strong>-" + discount + "%</strong></SPAN>";

}

function display_dicsount_old_price(total_price) {
    return "( Cena brez popusta: <SPAN style=\"text-decoration:line-through\">" + total_price + " €</SPAN> ) ";
}
// ----- END STEP 1 ---------------------

// ----- STEP 2 ---------------------
//----------------------------------
function on_btn_step2_next_click() {
    var chk_terms = $("INPUT[id$=chk_terms]");
    var message = $("SPAN#lbl_validate_step2_msg");
    var message2 = $("DIV#pogoji_poslovanja_ne");

    message.hide();
    message2.hide();
    
    if (chk_terms.attr("checked") == true) {
        var tab_strip = $find("ctl00_content_1_steps_tabs");

        var tabs = tab_strip.get_allTabs();
        tabs[2].enable();
        tabs[2].select();
        load_bill_data();
    }
    else {
        message.show();
        message2.slideDown();
    }
}
// ----- END STEP 2 ---------------------



// ----- STEP 3 ---------------------
//----------------------------------
function load_bill_data() {

    var data = $("INPUT[id$=data_selected_packet]").val();
    var url = "order_print.aspx?bill_data=" + data + "&ajax_load=true";

    var container = $("DIV#bill_part_container");
    container.html(get_loading_gif());

    $.get(url, function(postback_data) {

        container.hide();
        container.html(postback_data);
        container.slideDown();
    });

   

}

function round_number(num, dec) {
    var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
    return result;
}


function on_btn_step3_next_click() {
    $("DIV#shade_div").show();
    var message = $("DIV#waiting_message");
    message.centerInClient();
    message.fadeIn();
    
    
    return true;
}

function get_loading_gif()
{
    var load_gif = "<img class=\"img_ajax_loading\" src=\"../images/ajax_loading_small.gif\"/>";
    return load_gif;
}


