﻿/// <reference path="~/Assets/Javascripts/jquery-1.3.2-vsdoc.js" />

var chooseLanguage = function (container) {
    container.each(function () {
        var obj = $(this);
        obj.prev('a.countryLink').click(function (e) {
            $('#tooptipTemplate').hide();
            var languageSelector = $('#languageTemplate');
            languageSelector.css({ top: $(this).offset().top - 12 + 'px', left: $(this).offset().left + $(this).width() + 'px' });

            var html = "";
            $.each($(this).next().find("li"), function (index) {
                if (index > 0) {
                    html += "&nbsp;|&nbsp;";
                }

                html += "&nbsp;<a href=\"" + $(this).text() + "\" class=\"lang\">" + $(this).attr("title") + "</a>&nbsp;";
            });

            var languageContent = languageSelector.find('div.languageContent');
            languageContent.html(html);
            languageSelector.show();

            return false;
        });
    });
};

//var previousPage;
//var previousData;
//var tooltip = function (container) {
//    container.each(function () {
//        var obj = $(this);
//        var tooltip = $('#tooptipTemplate');
//        var windowObj = $(window);
//        obj.hover(function () {
//            var pageID = obj.prev('.page').text();
//            if (previousPage == pageID) {
//                showTooltip(windowObj, obj, tooltip, previousData);
//            }
//            else {
//                $.ajax({
//                    cache: true,
//                    dataType: "json",
//                    url: '/Assets/Services/CountrySelectorData.ashx?page=' + pageID,
//                    success: function (data) {
//                        previousPage = pageID;
//                        previousData = data;

//                        var html = "";
//                        $.each(data, function (index) {
//                            html += "<div class=\"column\">";
//                            html += "<h4>" + this.Title + "</h4>";
//                            html += "<p>";

//                            html += this.Header;
//                            html += "<br />";

//                            html += this.PhoneLabel + ": " + this.Phone;
//                            html += "<br />";

//                            if (this.Fax) {
//                                html += this.FaxLabel + ": " + this.Fax;
//                            }
//                            html += "<br />";

//                            if (this.Email) {
//                                html += this.EmailLabel + ": " + this.Email;
//                            }
//                            html += "<br />";

//                            if (this.Website) {
//                                html += this.WebsiteLabel + ": " + this.Website;
//                            }

//                            html += "</p>";
//                            html += "</div>";
//                        });
//                        html += "<span class=\"clear\"></span>";

//                        previousData = html;
//                        showTooltip(windowObj, obj, tooltip, html);
//                    }
//                });
//            }
//        },
//        function () {
//            tooltip.hide();
//        });
//    });
//};

var tooltip = function (container) {
    container.each(function () {
        var obj = $(this);
        var tooltip = $('#tooptipTemplate');
        var windowObj = $(window);
        obj.hover(function () {
            showTooltip(windowObj, obj, tooltip, obj.prev('div.partnerData').html());
        },
        function () {
            tooltip.hide();
        });
    });
};

var showTooltip = function (windowObj, obj, tooltip, data) {
    var tooltipContent = tooltip.find('div.tooltipContent');
    tooltipContent.html(data);

    var viewport = {
        x: windowObj.scrollLeft(),
        y: windowObj.scrollTop(),
        cx: windowObj.width(),
        cy: windowObj.height()
    };

    tooltip.css({ visibility: 'hidden' }).show();

    var helper = {
        offset: obj.offset(),
        height: tooltip.height(),
        width: tooltipContent.width() + 38
    };

    tooltip.css({ width: helper.width + 1000 }); // 1000 extra needen to fix width

    if (viewport.cy + viewport.y < helper.offset.top + helper.height + 10) {
        tooltip.css({ top: (helper.offset.top - helper.height - 10) + 'px' });
    } else {
        tooltip.css({ top: (obj.offset().top + 15) + 'px' });
    }

    if (viewport.cx + viewport.x < helper.offset.left + helper.width + 10) {
        tooltip.css({ left: (helper.offset.left - helper.width + 20) + 'px' });
    } else {
        tooltip.css({ left: obj.offset().left + 20 + 'px' });
    }

    tooltip.css({ visibility: 'visible' });
}

var laguangeSelector = function (obj) {
    obj.hover(function () {
        obj.find("img#globe").css({ backgroundPosition: '0px -17px' });
    }, function () {
        obj.find("img#globe").css({ backgroundPosition: '0px 0px' });
    });

    //        $(obj.parent()).click(function () {
    //            //var popup = obj.next("div#languagePopup");
    //            //popup.hide();
    //        });

    obj.click(function () {
        var popup = obj.next("div#languagePopup");
        popup.show();

        //        $("#wrapper").click(function () {
        //            popup.hide();
        //            obj.find("img#globe").css({ backgroundPosition: '0px 0px' });
        //        });
        return false;
    });
}

var sortSwf = function (id) {
    var text;
    var reg = /^\s*(?:[a\w\/\.\-\_\\#&%?=*+äåö]*).([jpg|mov|swf|mp4|png]{3})/i;
    if (id != '') {
        text = id;
        text = text.match(reg);
        text = $.trim(text[1]);
    } else {
        text = '';
    }
    switch (text) {
        case 'mov':
            return true;
            break;
        case 'flv':
            return true;
            break;
        case 'mp4':
            return true;
            break;
        case null:
            return false;
            break;
        case '':
            return false;
            break;
        case 'swf':
            return false;
            break;
        case 'png':
            return false;
            break;
        case 'jpg':
            return false;
            break;
        default:
            return false;
    }
};


function replaceCheckbox() {
    $('input[type=checkbox]').each(function() {
	    var checkbox = this;
	    var styleClass = "fancyCheckbox";
	    var styleClassChecked = "fancyCheckboxChecked";

	    var checkboxReplacement = $("<div/>")
	                                .addClass(styleClass)
                                    .click(function() {
                                        checkboxReplacement.toggleClass(styleClass)
	                                                       .toggleClass(styleClassChecked);
                                        checkbox.checked = !checkbox.checked;
                                    });

	    checkbox.checked = $(checkbox).attr("checked") == "checked"; // reset it to default
	    $(checkbox).css("position", "absolute")
	            .css("left", "-100000px")
	            .after(checkboxReplacement);
	});
}

//http://onehackoranother.com/projects/jquery/jquery-grab-bag/text-effects.html
$.fn.typewriter = function(options) {
    var settings = jQuery.extend({
        delay: 100,
        blinkerSpeed: 750
    }, options);

    this.each(function() {
        var $this = $(this), str = $this.text(), progress = 0;
        $this.text("");

        var timer = setInterval(function() {
        var blinker = "<span class=\"blinker\">_</span>";
            $this.html(str.substring(0, progress++) + blinker);
            if (progress > str.length) {
                clearInterval(timer);
            }
        }, settings.delay);

        var blink = setInterval(function() {
            $this.find("span.blinker").toggle();
        }, settings.blinkerSpeed);

    });
    return this;
};

var rssFeedScroll = function (container, options) {
    var feed = {
        items: [],
        currentIndex: 0,
        settings: null,
        init: function () {
            feed.settings = jQuery.extend({
                delay: 5000,
                url: ROOT_DIR + "Assets/Services/RssFeed.ashx",
                format: "&nbsp;&nbsp;<a href=\"$url$\">$title$</a>",
                maxTitleLength: 500
            }, options);

            if (feed.settings.id) {

                $.get(feed.settings.url, { pageid: feed.settings.id, lang: LANGUAGE_BRANCH }, function (data) {
                    $("entry", data).each(function () {
                        var item = { title: $("title", this).text(), url: $("link", this).attr("href") };
                        feed.items.push(item);

                    });

                    feed.scroll();
                }, "xml");
            }

        },
        scroll: function () {
            if (feed.items.length == 0) {
                return;
            }

            var currentItem = feed.items[feed.currentIndex];

            // cut if necessary
            var title = currentItem.title;

            var html = feed.settings.format.replace("$url$", currentItem.url).replace("$title$", title);
            container.html(html);
            /*
            performance issues?*/
            if (typeof ($.fn.typewriter) == "function") {
                container.find("a").typewriter({ delay: 1 });
            }


            if ((feed.currentIndex + 1) == feed.items.length) {
                feed.currentIndex = 0;
            } else {
                feed.currentIndex++;
            }

            setTimeout(function () { feed.scroll() }, feed.settings.delay);
        }
    };

    feed.init();
}

var caseHandler = function(options) {
    var handler = {
        settings: jQuery.extend({ containerId: 37, globalCaseContainer: null }, options),
        modes: { list: 100, grid: 200 },
        isEnabled: false,
        data: {},
        currentMode: null,
        selectedCategory: null,
        caseWidth: 162,
        caseHeight: 109,
        init: function() {
            if ($("#cases").length == 1) {
                $(".casesShowExample").bind("click", true, handler.toggleDropDown);
                $("#gridview").bind("click", function() { handler.showGrid(true); });
                $("#listview").bind("click", function() { handler.showList(true); });
                $("#selectImage").bind("click", function() { $(this).next().toggle(); return false; });
                $(".chooseSector li").bind("click", function() {
                    handler.selectedCategory = $(this).attr("value");
                    handler.getCurrentCategory();
                    $(this).closest("ul").toggle();
                });
                handler.currentMode = handler.modes.grid;
                handler.getAll();
            }
        },

        getCurrentCategory: function() {
            $.get(ROOT_DIR + "Assets/Services/CaseStudiesService.svc/GetFiltered", { containerId: handler.settings.containerId, globalCaseContainer: handler.settings.globalCaseContainer, category: handler.selectedCategory }, function(data) {
                handler.data = data;
                handler.updateView(true);
            }, "json");
        },

        getAll: function() {
            $.get(ROOT_DIR + "Assets/Services/CaseStudiesService.svc/GetAll", { containerId: handler.settings.containerId, globalCaseContainer: handler.settings.globalCaseContainer }, function(data) {
                handler.data = data;
                handler.updateView();
            }, "json");
        },

        toggleDropDown: function(includeHeader, callback) {
            if (handler.isEnabled) {
                $("#casesDropDown").slideUp("slow", function() {
                    if (typeof (callback) == "function") {
                        callback();
                    }
                });
                if (includeHeader) {
                    $("#casesHeader .expanded").fadeOut("fast", function() {
                        $("#casesHeader .default").fadeIn("fast");
                    });
                }
                handler.isEnabled = false;
            } else {
                $("#casesDropDown").slideDown("slow", function() {
                    if (typeof (callback) == "function") {
                        callback();
                    }
                });
                if (includeHeader) {
                    $("#casesHeader .default").fadeOut("fast", function() {
                        $("#casesHeader .expanded").fadeIn("fast");
                    });

                }
                handler.isEnabled = true;
            }
        },

        toggleMode: function(smoothly) {
            if (handler.currentMode == handler.modes.grid) {
                handler.currentMode = handler.modes.list;
            } else {
                handler.currentMode = handler.modes.grid;
            }
            handler.updateView(smoothly);
        },

        updateView: function(smoothly) {
            if (handler.currentMode == handler.modes.grid) {
                handler.showGrid(smoothly);
            }
            else if (handler.currentMode == handler.modes.list) {
                handler.showList(smoothly);
            }
        },

        showGrid: function(smoothly) {
            var html = $("<ul id=\"caseGrid\"></ul>");
            $.each(handler.data, function(i) {
                var itemHtml = "<a href=\"#" + this.ID + "\"><img src=\"" + ROOT_DIR + "Assets/Services/ImageResize.ashx?width=" + handler.caseWidth + "&height=" + handler.caseHeight + "&enforceheight=true&path=" + this.Thumbnail + "\" alt=\"" + this.Header + "\" width=\"" + handler.caseWidth + "\" height=\"" + handler.caseHeight + "\"/></a>";

                if (i % 5 == 0) {
                    html.append("<li value=\"" + this.Category + "\" class=\"first\">" + itemHtml + "</li>");
                } else {
                    html.append("<li value=\"" + this.Category + "\">" + itemHtml + "</li>");
                }
            });
            html.append("<br class=\"clear\"/>");

            if (smoothly) {
                handler.toggleDropDown(false, function() {
                    $("#caseDropBg").html(html);
                    handler.toggleDropDown(false);
                });
            } else {
                $("#caseDropBg").html(html);
            }
        },

        showList: function(smoothly) {
            var html = $("<div id=\"tableWrap\"><div id=\"caseList\"></div></div>");
            $.each(handler.data, function(i) {
                html.append("<ul class=\"wraps\" value=\"" + this.Category + "\">" +
                            "<li class=\"header\">" + this.Header + "</li>" +
                            "<li class=\"content\"><span>" + CASE_CATEGORIES[this.Category] + "</span><br/><p>" + this.Introduction + "</p></li>" +
                            "<li class=\"more\"><a href=\"#" + this.ID + "\" class=\"blackArrowLink\">" + TRANSLATE_MORE + "</a></li>" +
                        "</ul>");
                 });
            html.append("<br class=\"clear\"/>");
            $(html).find(".content").truncate_startpage(200);
            $(html).find("img").remove();
            if (smoothly) {
                handler.toggleDropDown(false, function() {
                    $("#caseDropBg").html(html);
                    handler.toggleDropDown(false);
                });
            } else {
                $("#caseDropBg").html(html);
            }
        }
    };

    handler.init();
}

function createLightBox() {
    var lightbox = {
        defaultOptions: {
            width: 600,
            height: 400,
            container: null,
            trigger: "#show_lb_content",
            content: "#lb_content",
            closeImage: ROOT_DIR + "Assets/Images/cross.png",
            tellFriendText: null,
            backText: null,
            linkDivWidth: 600,
            linkDivHeight: 50,
            contactText: null,
            readMoreText: null,
            sendText: null,
            tellFriendrErorText: null,
            tellFriendEmptyMessage: null,
            pageId: START_PAGE,
            globalPage: null
        },
        $containerPlaceholder: null,
        init: function(options) {
            this.options = $.extend(this.defaultOptions, options);

            var that = this;
            this.options.height += 10;
            $(this.options.trigger).live("click", function() {
                var tmp = $(this).attr("href").split("#");
                var substr = tmp[tmp.length - 1];
                $.get(ROOT_DIR + "Assets/Services/CaseStudiesService.svc/GetCase", { pageLink: substr }, function(data) {
                    that.setup(data);
                    that.show(data);
                }, "json");

                return false;
            });
        },
        setup: function(dataItem) {
            that = this;
            $("#casesWrapper").show();
            $("#tellFriendWrapper").hide();
            $("#left h2", that.options.content).text(dataItem.Header);
            $("#left .innerBody", that.options.content).html(dataItem.Body);
            $("#left .innerBody").find("img").remove();
            $("#left .innerBody").truncate_startpage(300);
            $("#right img", that.options.content).attr("src", dataItem.Image)
                                                 .attr("alt", dataItem.Header);
            if (typeof (Cufon) === "function")
                Cufon.refresh();
        },
        show: function(dataItem) {
            that = this;
            $(that.options.containerDiv).show("fast", function() {
                if (that.$containerPlaceholder == null) {
                    if (that.options.container != null) {
                        // create the placeholder that keeps track of the content to show
                        var $placeholder = $(document.createElement("div"));
                        $placeholder.addClass("placeholder");
                        that.$containerPlaceholder = $placeholder;
                        // get the container of the lightbox
                        var $outerContainer = $(that.options.container);
                        // create the overlay container that has the same dimensions as the lightbox outer container contains the inner container
                        var $overlay = $(document.createElement("div"));
                        $overlay.width($outerContainer.width()).height($outerContainer.height()).addClass("overlay");
                        $overlay.click(function() {
                            $content.hide();
                            $(that.$containerPlaceholder).replaceWith($content);
                            that.$containerPlaceholder = null;
                            $overlay.remove();
                        })

                        // create an inner container with the specified width and height
                        var $innerContainer = $(document.createElement("div"));
                        $innerContainer.width(that.options.width).height(that.options.height);
                        var left = ($outerContainer.width() - that.options.width) / 2;
                        var top = ($outerContainer.height() - that.options.height) / 2;
                        $innerContainer.addClass("innerContainer");
                        $innerContainer.css("top", top).css("left", left);
                        $innerContainer.click(function(event) {
                            event.stopPropagation();
                        });
                        $closeButton = $("<input type='image' src='" + that.options.closeImage + "' class='closeButton'>");
                        $innerContainer.append($closeButton);
                        $closeButton.click(function() {
                            $content.hide();
                            $(that.$containerPlaceholder).replaceWith($content);
                            that.$containerPlaceholder = null;
                            $overlay.remove();
                        });

                        // create an inner container for the links

                        var $innerLinks = $(document.createElement("div"));
                        $innerLinks.width(that.options.linkDivWidth).height(that.options.linkDivHeight);
                        var left = 40;
                        var top = 216;
                        $innerLinks.addClass("links");
                        $innerLinks.css("top", top).css("left", left);

                        $tellFriend = $("<p class='tellFriend blackArrowLink'>" + that.options.tellFriendText + "</p>");
                        var linkTarget = dataItem.URL;
                        if (that.options.globalPage != -1) {
                            if (linkTarget.indexOf("Int") == 0 || linkTarget.indexOf("int")) {
                                $readMore = $("<a href='" + dataItem.URL + "' class='url blackArrowLink' target='_blank'>" + that.options.readMoreText + "</a>");
                            }
                            else {
                                $readMore = $("<a href='" + dataItem.URL + "' class='url blackArrowLink'>" + that.options.readMoreText + "</a>");
                            }
                        }
                        else {
                            $readMore = $("<a href='" + dataItem.URL + "' class='url blackArrowLink'>" + that.options.readMoreText + "</a>");
                        }
                        //$contact = $("<a href='" + dataItem.ContactURL + "' class='contact blackArrowLink'>" + that.options.contactText + "</a>");
                        $send = $("<p class='send blackArrowLink' style='display:inline'>" + that.options.sendText + "</p>")

                        $send.hide();
                        $("#messageSentWrapper").hide();

                        // Tell a friend click event
                        $tellFriend.click(function() {
                            $("#casesWrapper").hide();
                            $("#tellFriendWrapper").toggle();
                            $tellFriend.hide();
                            $readMore.toggle();
                            $send.toggle();
                            //$contact.hide();
                        });

                        // Validate and send the message
                        $send.click(function() {
                            var toEmailAddress = document.getElementById("toEmailAddress").value;
                            var fromEmailAddress = document.getElementById("fromEmailAddress").value;
                            var emailMessage = document.getElementById("emailMessage").value;

                            var validateErrorTo = document.getElementById("validateErrorTo");
                            var validateErrorFrom = document.getElementById("validateErrorFrom");
                            var validateMessage = document.getElementById("validateMessage");
                            var validateSend = document.getElementById("validateSend");

                            var errorText = that.options.tellFriendrErorText;
                            var emptyMessage = that.options.tellFriendEmptyMessage;

                            if (!IsValidEmail(toEmailAddress) || toEmailAddress == "") {
                                validateErrorTo.innerHTML = errorText;
                            }
                            else {
                                validateErrorTo.innerHTML = "";
                            }

                            if (!IsValidEmail(fromEmailAddress) || fromEmailAddress == "") {
                                validateErrorFrom.innerHTML = errorText;
                            }
                            else {
                                validateErrorFrom.innerHTML = "";
                            }

                            if (emailMessage == "") {
                                validateMessage.innerHTML = emptyMessage;
                            }
                            else {
                                validateMessage.innerHTML = "";
                            }

                            if (IsValidEmail(toEmailAddress) && IsValidEmail(fromEmailAddress) && !emailMessage == "") {

                                $.get(ROOT_DIR + "Assets/Services/UtilService.svc/TellAFriend", { pageId: that.options.pageId, to: toEmailAddress, from: fromEmailAddress, text: emailMessage, url: dataItem.URL }, function(result) {
                                    $("#tellFriendWrapper").toggle();
                                    $("#messageSentWrapper").toggle();
                                    $send.hide();
                                    validateSend.innerHTML = result.Message;
                                    $.doTimeout(3000, function() {
                                        $content.hide();
                                        $(that.$containerPlaceholder).replaceWith($content);
                                        that.$containerPlaceholder = null;
                                        $overlay.remove();
                                    })
                                }, "json");
                            }
                        });

                        $innerContainer.append($innerLinks);

                        $innerLinks.append($send);
                        $innerLinks.append($readMore);
                        //$innerLinks.append($contact);
                        $innerLinks.append($tellFriend);


                        // replace (and get) the contentObject with the placeholder
                        var $content = $(that.options.content).replaceWith($placeholder);
                        // place the content inside the inner container and show it
                        $innerContainer.hide();
                        $innerContainer.append($content);
                        // place the inner container inside the overlay
                        $overlay.append($innerContainer);
                        // place the overlay inside the outer container
                        $outerContainer.append($overlay);
                        $innerContainer.slideDown("slow", function() { $content.show(); $.scrollTo($content, 500, { offset: { top: -100} }); });
                    } else {
                        // this is the usual lightbox
                        // create the placeholder that keeps track of the content to show
                        var $placeholder = $(document.createElement("div"));
                        $placeholder.addClass("placeholder");
                        that.$containerPlaceholder = $placeholder;
                        // get the container of the lightbox
                        var $outerContainer = $(window);
                        // create the overlay container that has the same dimensions as the lightbox outer container contains the inner container
                        var $overlay = $(document.createElement("div"));
                        $overlay.css("top", $(window).scrollTop());
                        $overlay.css("left", $(window).scrollLeft());
                        $overlay.width($outerContainer.width()).height($outerContainer.height()).addClass("overlay");
                        $overlay.click(function() {
                            $content.hide();
                            $(that.$containerPlaceholder).replaceWith($content);
                            that.$containerPlaceholder = null;
                            $overlay.remove();
                        })

                        // create an inner container with the specified width and height
                        var $innerContainer = $(document.createElement("div"));
                        $innerContainer.width(that.options.width).height(that.options.height);
                        var left = ($outerContainer.width() - that.options.width) / 2;
                        var top = ($outerContainer.height() - that.options.height) / 2;
                        $innerContainer.addClass("innerContainer");
                        $innerContainer.css("top", top).css("left", left);
                        $innerContainer.click(function(event) {
                            event.stopPropagation();
                        });

                        $(window).resize(function() {
                            $overlay.width($outerContainer.width()).height($outerContainer.height());
                            var left = ($outerContainer.width() - that.options.width) / 2;
                            var top = ($outerContainer.height() - that.options.height) / 2;
                            left = (left < 0) ? "0" : left;
                            top = (top < 0) ? "0" : top;
                            $innerContainer.css("top", top).css("left", left);
                        });

                        $(window).scroll(function() {
                            if ($overlay.width() >= $innerContainer.width()) {
                                $overlay.css("left", $(window).scrollLeft());
                            }
                            if ($overlay.height() >= $innerContainer.height()) {
                                $overlay.css("top", $(window).scrollTop());
                            }
                            $overlay.width($outerContainer.width()).height($outerContainer.height());
                            var left = ($outerContainer.width() - that.options.width) / 2;
                            var top = ($outerContainer.height() - that.options.height) / 2;
                            left = (left < 0) ? "0" : left;
                            top = (top < 0) ? "0" : top;
                            $innerContainer.css("top", top).css("left", left);
                        });

                        $closeButton = $("<img src='" + that.options.closeImage + "' alt='close' class='closeButton'>");
                        $closeButton.click(function() {
                            $content.hide();
                            $(that.$containerPlaceholder).replaceWith($content);
                            that.$containerPlaceholder = null;
                            $overlay.remove();
                        });
                        $innerContainer.append($closeButton);

                        // replace (and get) the contentObject with the placeholder
                        var $content = $(that.options.content).replaceWith($placeholder);
                        // place the content inside the inner container and show it
                        $innerContainer.append($content);
                        $content.hide();
                        $innerContainer.hide();
                        // place the inner container inside the overlay
                        $overlay.append($innerContainer);
                        // place the overlay inside the outer container
                        $("body").append($overlay);
                        $innerContainer.slideDown("slow", function() { $content.show(); });
                    }

                    Cufon.refresh('.links a')('.links a')('.links p');
                }
            });
        }
    }
    return lightbox;
}

var setActiveMenuItem = function(listItem) {
    var parent = $("#header");
    var menuItem = listItem.children(".mainMenuItem")
    var offset = parent.offset().left - menuItem.offset().left;
    listItem.prev().css("background-color", "#FFF");
    listItem.next().css("background-color", "#FFF");
    menuItem.css("background", "transparent url(" + ROOT_DIR + "Assets/Images/header-hover.png) no-repeat " + offset + "px top");
};

var quickSearchHandler = function(options) {
    var handler = {
        settings: jQuery.extend({
            minChars: 3,
            maxHits: 10,
            textboxSelector: "#searchBox :text",
            startPageLink: START_PAGE,
            loaderSelector: "#searchLoader",
            dropdownSelector: "#searchDropDown",
            changeHandlerTimeout: 100

        }, options),
        lastQuery: "",
        textbox: null,
        changeDetection: false,
        init: function() {
            handler.textbox = $(handler.settings.textboxSelector)
                                .val("")
                                .attr("autocomplete", "off")
                                .focus(function() {
                                    handler.changeDetection = true; 
                                })
                                .blur(function() {
                                    $.doTimeout(250, function() { // delay to make sure click events are triggered
                                        handler.changeDetection = false;
                                    }) 
                                }); 
            handler.changeHandler();
        },
        changeHandler: function() {
            $.doTimeout(handler.changeHandlerTimeout, function() {
                if (handler.changeDetection) {
                    var query = $.trim(handler.textbox.val());
                    if (!String.IsNullOrEmpty(handler.lastQuery)) {
                        handler.searchHandler(query);
                    }

                    handler.lastQuery = query;
                } else {
                    handler.hide();
                }

                return true;
            });
        },
        searchHandler: function(query) {
            if (query.length >= handler.settings.minChars) {
                if (query != handler.lastQuery) {
                    handler.search(query);
                }

                handler.show();
            } else {
                handler.hide();
            }
        },
        search: function(query) {
            var dropdown = $(handler.settings.dropdownSelector);
            var list = dropdown.find("ul").hide();
            var loader = $(handler.settings.loaderSelector).show();

            $.get(ROOT_DIR + "Assets/Services/SearchService.svc/Search", { startPageLink: handler.settings.startPageLink, query: query, maxHits: handler.settings.maxHits, language: LANGUAGE_BRANCH }, function (data) {
                // do something with the result;
                list.html("");
                if (data.length > 0) {
                    var html = "";
                    $.each(data, function() {
                        html += sprintf("<li><a href=\"%1$s\" title=\"%2$s\">%2$s</a></li>", this.URL, this.Header);
                    });
                    list.append(html);
                } else {
                    list.append(sprintf("<li>%s<br/>%s</li>", TRANSLATE_SEARCH_NO_HITS, TRANSLATE_SEARCH_TRY_AGAIN));
                }

//                var link = dropdown.find("a.searchLink");
//                link.attr("href", link.attr("href").replace(/\?q=(.*)/g, "?q=" + query));

                loader.hide();
                list.show();
            }, "json");
        },
        show: function() {
            $(handler.settings.dropdownSelector).show();
        },
        hide: function() {
            $(handler.settings.dropdownSelector).hide();
        }
    };

    handler.init();
}

var searchPaging = function(options) {
    var handler = {
        settings: jQuery.extend({
            itemsPerPage: SEARCH_ITEMS_PER_PAGE,
            startPageLink: START_PAGE,
            loaderSelector: "#searchLoader",
            containerSelector: "#searchResult",
            moreButtonSelector: ".buttonWide",
            query: null
        }, options),
        fetchPage: function(page) {
            var loader = $(handler.settings.loaderSelector);
            loader.show();

            $.get(ROOT_DIR + "Assets/Services/SearchService.svc/SearchWithPaging", { startPageLink: handler.settings.startPageLink, query: handler.settings.query, itemsPerPage: handler.settings.itemsPerPage, page: page, language: LANGUAGE_BRANCH }, function (result) {
                var container = $(handler.settings.containerSelector);
                var html = "";
                $.each(result.Items, function() {
                html += sprintf("<h3>%s</h3><div class=\"content\">%s</div><p><a href=\"%s\">%s</a><p><img src='/Assets/Images/newsSeparator.png' alt='separator' />",
                    this.Header, (!String.IsNullOrEmpty(this.Introduction) ? this.Introduction : ""), this.URL, TRANSLATE_READ_MORE);
                });
                html = $(html);
                container.append(html.hide()); this.URL,
                Cufon.refresh('.contentBox h3');
                html.slideDown();


                var moreButton = $(handler.settings.moreButtonSelector);
                if (!result.HasMore) {
                    moreButton.fadeOut();
                }

                loader.hide();
            }, "json");

        }
    };

    return handler;
}

var newsPaging = function(options) {
    var handler = {
        settings: jQuery.extend({
            itemsPerPage: SEARCH_ITEMS_PER_PAGE,
            startPageLink: START_PAGE,
            loaderSelector: "#searchLoader",
            containerSelector: ".newsItem",
            moreButtonSelector: ".buttonWide"
        }, options),
        fetchPage: function(page) {
            var loader = $(handler.settings.loaderSelector);
            loader.show();

            $.get(ROOT_DIR + "Assets/Services/NewsService.svc/NewsWithPaging", {
                startPageLink: handler.settings.startPageLink,
                itemsPerPage: handler.settings.itemsPerPage,
                page: page,
                language: LANGUAGE_BRANCH
            },
                     function(result) {
                         var container = $(handler.settings.containerSelector);
                         $.each(result.Items,
                            function() {
                                var item = $('<div class="newsDate">' + this.Date + '</div>' +
                                            '<a class="newsTitle" href="#">' + this.Header + '</a>' +
                                            '<div class="newsContent">' +
                                                '<p class="jTrunc">' +
                                                    this.Introduction +
                                                '</p>' +
                                            '</div>' +
                                            '<div class="newsButton">' +
                                                '<p class="readMore json">' +
                                                    '<a href="' + this.URL + '">&nbsp;&nbsp;&nbsp;' + TRANSLATE_READ_MORE + '<img class="json" src="/Assets/Images/arrowRight.png" alt="arrow" /></a>' +
                                                '</p>' +
                                            '</div>' +
                                            '<img src="/Assets/Images/newsSeparator.png" alt="separator" />');
                                container.append(item);
                                $(container).find(".newsContent p.jTrunc").truncate(200);
                                Cufon.refresh('p.readMore');
                                item.slideDown();

                            });

                         var moreButton = $(handler.settings.moreButtonSelector);
                         if (!result.HasMore) {
                             moreButton.fadeOut();
                         }
                     }, "json");

        }
    };

    return handler;
}


// borrowed functions

String.IsNullOrEmpty = function(value) {
    var isNullOrEmpty = true;
    if (value) {
        if (typeof (value) == 'string') {
            if (value.length > 0)
                isNullOrEmpty = false;
        }
    }
    return isNullOrEmpty;
}

/**
 * sprintf() for JavaScript v.0.4
 *
 * Copyright (c) 2007 Alexandru Marasteanu <http://alexei.417.ro/>
 * Thanks to David Baird (unit test and patch).
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02111-1307 USA
 */

function str_repeat(i, m) { for (var o = []; m > 0; o[--m] = i); return(o.join('')); }

function sprintf() {

  var i = 0, a, f = arguments[i++], o = [], m, p, c, x;
  while (f) {
    if (m = /^[^\x25]+/.exec(f)) o.push(m[0]);
    else if (m = /^\x25{2}/.exec(f)) o.push('%');
    else if (m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f)) {
      if (((a = arguments[m[1] || i++]) == null) || (a == undefined)) throw("Too few arguments.");
      if (/[^s]/.test(m[7]) && (typeof(a) != 'number'))
        throw("Expecting number but found " + typeof(a));
      switch (m[7]) {
        case 'b': a = a.toString(2); break;
        case 'c': a = String.fromCharCode(a); break;
        case 'd': a = parseInt(a); break;
        case 'e': a = m[6] ? a.toExponential(m[6]) : a.toExponential(); break;
        case 'f': a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a); break;
        case 'o': a = a.toString(8); break;
        case 's': a = ((a = String(a)) && m[6] ? a.substring(0, m[6]) : a); break;
        case 'u': a = Math.abs(a); break;
        case 'x': a = a.toString(16); break;
        case 'X': a = a.toString(16).toUpperCase(); break;
      }
      a = (/[def]/.test(m[7]) && m[2] && a > 0 ? '+' + a : a);
      c = m[3] ? m[3] == '0' ? '0' : m[3].charAt(1) : ' ';
      x = m[5] - String(a).length;
      p = m[5] ? str_repeat(c, x) : '';
      o.push(m[4] ? a + p : p + a);
    }
    else throw ("Invalid format");
    f = f.substring(m[0].length);
  }
  return o.join('');
}

//http://codeasp.net/blogs/raghav_khunger/microsoft-net/369/regular-expression-for-email-with-jquery
function IsValidEmail(email) {
    var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    return filter.test(email);

}

