﻿jQuery.extend({
    unparam: function (query) {
        var query_string = {};
        if (query != null) {
            var vars = query.split("&");
            for (var i = 0; i < vars.length; i++) {
                var pair = vars[i].split("=");
                pair[0] = decodeURIComponent(pair[0]);
                pair[1] = decodeURIComponent(pair[1]);
                // If first entry with this name   
                if (typeof query_string[pair[0]] === "undefined") {
                    query_string[pair[0]] = pair[1];
                    // If second entry with this name 
                } else if (typeof query_string[pair[0]] === "string") {
                    var arr = [query_string[pair[0]], pair[1]];
                    query_string[pair[0]] = arr;
                    // If third or later entry with this name  
                } else {
                    query_string[pair[0]].push(pair[1]);
                }
            }
        }
        return query_string;
    }
});

function EventTarget(name) {
    this._listeners = [];
}

EventTarget.prototype = {
    constructor: EventTarget,
    addListener: function (listener) {
        this._listeners.push(listener);
    },
    fire: function (args) {
        if (this._listeners instanceof Array) {
            for (var i = 0, len = this._listeners.length; i < len; i++) {
                this._listeners[i].call(args);
            }
        }
    },
    removeListener: function (listener) {
        for (var i = 0, len = this._listeners.length; i < len; i++) {
            if (this._listeners[i] === listener) {
                this._listeners.splice(i, 1);
                break;
            }
        }
    }
};

var Total = {
    State: {
        init: function () {
            $.History.bind(function (state) {
                var tmp = $.unparam(state);
                if (tmp) {
                    Total.State.current = tmp.hstr_state;
                    Total.State.data = tmp;
                }
                Total.State.changed.fire();
            });
        },
        change: function (state, data) {
            data.hstr_state = state;
            var encoded = $.param(data);
            $.History.go(encoded);
        },
        changed: new EventTarget(),
        data: null,
        current: null
    },
    Paging: {
        pageSize: 10,
        currentPage: 1,
        totalRows: 0,
        pageChanged: new EventTarget()
    },
    Sorting: {
        sortOrder: 'asc',
        sortBy: '',
        sortChanged: new EventTarget()
    },
    SearchDialog: {
        tabChanged: new EventTarget(),
        currentTab: '',
        Products: {
            loadData: new EventTarget()
        },
        Brands: {
            loadData: new EventTarget()
        },
        Categories: {
            loadData: new EventTarget()
        }
    },
    Util: {
        searchResult: function () {
        },
        setDefaultText: function (textbox, text) {
            /* podešavanje defaultnog texta u textbox (tekst koji se prikazuje ako ništa drugo nije upisano) */

            $(textbox).val(text)
            $(textbox).focus(function () {
                if ($(this).val() == text) $(this).val('');
            });
            $(textbox).blur(function () {
                if ($(this).val() == '') $(this).val(text);
            });
        },
        replaceAll: function (text, searchFor, replaceWith) {
            while (text.indexOf(searchFor) != -1) { text = text.replace(searchFor, replaceWith); }
            return text;
        }
    }
};
Total.State.init();

function LoadAjaxIntoDialog(dialogElementSel, url, params, width, height) {
    $(dialogElementSel).dialog({
        title: '',
        resizable: false,
        height: height,
        width: width
    });
    $(dialogElementSel).load(url, params);
}

function EnsureGoogleMaps(callback) {
    $(document).ready(function () {
        if (typeof google === 'undefined' || typeof google.maps === 'undefined') {
            $.getScript('http://maps.google.com/maps/api/js?sensor=false&callback=' + callback);
        } else {
            eval(callback + '()');
        }
    });
}

function GoogleMapsAutoCenter(map, markers) {
    var bounds = new google.maps.LatLngBounds();
    $.each(markers, function (index, marker) {
        bounds.extend(marker.position);
    });
    map.fitBounds(bounds);
}

$.validator.setDefaults({
    highlight: function (input) {
        $(input).addClass("ui-state-highlight");
    },
    unhighlight: function (input) {
        $(input).removeClass("ui-state-highlight");
    },
    errorClass: "ui-state-error"
});

jQuery.extend(jQuery.validator.messages, {
    required: "Unos je obavezan",
    remote: "Unos nije ispravan",
    email: "Molimo upišite ispravnu e-mail adresu",
    url: "Molimo upišite ispravan URL",
    date: "Molimo upišite ispravan datum",
    dateISO: "Molimo upišite ispravan datum (ISO)",
    number: "Potrebno je upisati broj",
    digits: "Potrebno je upisati broj",
    creditcard: "Molimo upišite ispravan broj kreditne kartice",
    equalTo: "Unesene vrijednosti nisu jednake",
    accept: "",
    maxlength: $.validator.format("Moguće je upisati maksimalno {0} znakova"),
    minlength: $.validator.format("Molimo upišite više od {0} znakova"),
    rangelength: $.validator.format("Molimo upišite između {0} i {1} znakova"),
    range: $.validator.format("Molimo upišite vrijednost između {0} i {1}"),
    max: $.validator.format("Molimo upišite vrijednost manju od {0}"),
    min: $.validator.format("Molimo upišite vrijednost veću od {0}")
});

$(document).ready(function () {
    $('input').keypress(function (e) {
        var c = e.which ? e.which : e.keyCode;
        if (c == 13) {
            // pritisnut je ENTER, radimo submit forme
            if (this.form) {
                this.form.submit();
                e.preventDefault();
                return false;
            }
        }
    });

    $("input, textarea").addClass("idle");
    $("input, textarea").live('focus', function () {
        $(this).addClass("activeField").removeClass("idle");
    })
    $("input, textarea").live('blur', function () {
        $(this).removeClass("activeField").addClass("idle");
    });
});

// simuliranje klika na neki element kada se u textboxu (bilo kojem input polju) pritisne enter
function performClickOnEnter(inputElementSelector, targetElementSelector) {
    $(inputElementSelector).keypress(function (e) {
        var c = e.which ? e.which : e.keyCode;
        if (c == 13) {
            // pritisnut je ENTER
            $(targetElementSelector).click();
            e.preventDefault();
            return false;
        }
    });
}

function setupAutocomplete(params) {
    var loadingData = false;

    var autocomplete = $('body > #autocomplete');
    if (autocomplete.length < 1) {
        var template = '\
        <div id="autocomplete" style="display: none; position: absolute; width: 407px;">\
        <table border="0" cellpadding="0" cellspacing="0">\
        <tr>\
        <td style="background: url(\'/Content/Styles/images/tooltip_top.png\') repeat scroll 0% 0% transparent; height: 44px; text-align: right; vertical-align: bottom;" align="right" valign="bottom">\
            <a href="#" id="autocomplete_close" style="display: block; width: 16px; height: 16px; float: right; margin-right: 10px;"><span class="ui-icon ui-icon-closethick"></span></a>&nbsp;\
        </td>\
        </tr>\
        <tr>\
        <td style="Background: url(\'/Content/Styles/images/tooltip_middle.png\');">\
            <div style="list-style: none; padding-left: 10px; padding-right: 10px; max-height: 200px; width: 380px; overflow: auto;">\
            <ul id="autocomplete_list" style="list-style: none; padding-left: 10px; padding-right: 10px;"></ul>\
        </td>\
        </tr>\
        <tr>\
        <td>\
        <img border="0" src="/Content/Styles/images/tooltip_bottom.png" >\
        </td>\
        </tr>\
        </table>\
        </div>';

        autocomplete = $(template);
        $('body').append(autocomplete);
    }

    var close = function () {
        autocomplete.hide();
        if (params.closed) {
            params.closed();
        }
    };

    var input = $(params.input);
    var autocomplete_list = autocomplete.find('#autocomplete_list');
    var currentData = null;

    $('#autocomplete_close', autocomplete).click(function (e) {
        close();

        e.preventDefault();
        return false;
    });

    var loadData = function (force) {
        if (loadingData || (!force && input.val().length < params.minLength)) { return; }

        loadingData = true;
        close();
        input.addClass('autocomplete_loading');


        var url = params.url;

        if (params.beforeSend) {
            var ret = params.beforeSend(params);
            if (ret && ret.url) {
                url = ret.url;
            }
        }
        $.ajax({
            url: url,
            type: 'POST',
            data: { term: input.val() },
            success: function (data) {
                autocomplete_list.empty();
                var show = false;
                if (data.Items && data.Items.length > 0) {
                    currentData = data;

                    for (var i = 0; i < currentData.Items.length; i++) {
                        var item = currentData.Items[i];
                        var itemEl;
                        if (item.Type != "headline") {
                            itemEl = $('<a href="#" data_index="' + i + '" style="padding-left: 10px; display: block;">' + item.Text.replace("'", "") + '</a>');
                        } else {
                            itemEl = $('<span>' + item.Text.replace("'", "") + '</span>');
                        }
                        var listItem = $('<li class="autocomplete_item"></li>');

                        autocomplete_list.append(listItem);
                        listItem.append(itemEl);
                    }
                    autocomplete_list.find('a').click(function (e) {
                        e.preventDefault();

                        var index = $(this).attr('data_index');
                        var item = currentData.Items[index];

                        if (item.Url && item.Url != null && item.Url != "") {
                            location.href = item.Url;
                            return;
                        }

                        input.val(item.Text);
                        if (params.selected) {
                            params.selected(item);
                        }

                        close();

                        return false;
                    });

                    show = true;
                } else {
                    // nema podataka
                    if (params.noRowsInfo) {
                        autocomplete_list.append('<li class="autocomplete_item">' + params.noRowsInfo + '</li>');
                        show = true;
                    }
                }

                if (show) {
                    autocomplete.show(0, function () {
                        // nije greška, treba pozivati 2x, bug neki
                        autocomplete.position({ of: params.input, my: 'left top', at: 'left bottom', offset: '', collision: 'none' });
                        autocomplete.position({ of: params.input, my: 'left top', at: 'left bottom', offset: '', collision: 'none' });
                    });
                }
            },
            complete: function () {
                input.removeClass('autocomplete_loading');
                loadingData = false;
            }
        });
    };

    input.keyup(function () {
        loadData(false);
    });

    if (params.buttonSelectors) {
        $(params.buttonSelectors).click(function () {
            loadData(false);
        });
    }

    var isFocused = false;
    autocomplete.find('*').add(input).focus(function () {
        isFocused = true;
    });
    autocomplete.find('*').add(input).blur(function () {
        isFocused = false;

        setTimeout(function () {
            if (!isFocused) {
                close();
            }
        }, 100);
    });
}

function rnd() {
    return (Math.floor(Math.random() * 101));
}

function highlightInPage(selector, highlightTerm) {
    // originalni highlight
    $(selector).highlight(highlightTerm);

    // highligh sa hr znakovima (ovo je best guess i nije bulletproof)
    // osiguravamo da se napravi highlight i onih riječi koje imaju čćžšđ u sebi (npr. čizma i cizma)
    var chars = 'c:č,c:ć,z:ž,s:š,d:đ';
    var charArray = chars.split(',');
    for (var i = 0; i < charArray.length; i++) {
        var term = highlightTerm.replace(charArray[i].split(':')[0], charArray[i].split(':')[1]);
        $(selector).highlight(term);
    }
}
