$.Hashtable = function () {
    this.items = new Array();
    this.itemsCount = 0;
    this.add = function (key, value) {
        if (!this.containsKey(key)) {
            this.items[key] = value;
            this.itemsCount++;
        }
        else throw "key '" + key + "' allready exists."
    }
    this.get = function (key) {
        if (this.containsKey(key)) return this.items[key];
        else return null;
    }

    this.remove = function (key) {
        if (this.containsKey(key)) {
            delete this.items[key];
            this.itemsCount--;
        }
        else throw "key '" + key + "' does not exists."
    }
    this.containsKey = function (key) {
        return typeof (this.items[key]) != "undefined";
    }
    this.containsValue = function containsValue(value) {
        for (var item in this.items) {
            if (this.items[item] == value) return true;
        }
        return false;
    }
    this.contains = function (keyOrValue) {
        return this.containsKey(keyOrValue) || this.containsValue(keyOrValue);
    }
    this.clear = function () {
        this.items = new Array();
        itemsCount = 0;
    }
    this.size = function () {
        return this.itemsCount;
    }
    this.isEmpty = function () {
        return this.size() == 0;
    }
};

var ask = function (q, url) {
    if (confirm(q)) window.location = url;
}

var emailfielddefaultvalue = '';

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

$(document).ready(function () {
    $('.doSubmit').click(function (e) {
        $("#frmOgone").submit();
    });
		
	$('#ctl00_Content_btnGenerateExcel').click(function (e) {
        $("#ctl00_Content_btnGenerateExcel").css('display', 'none');
		$("#loading").css('display', 'block');
    });

    $('#ctl00_Content_searchRMA').keyup(function (e) {
        $.ajax({
            url: '/searchresult.aspx?text=' + $('#ctl00_Content_searchRMA').val(),
            success: function (data) {
                $('#searchDIV').html(data);
                $('#searchDIV').css('display', 'block');

                $('.select').click(function (e) {
                    $('#ctl00_Content_searchRMA').val($(this).attr("title"));
                    $('#searchDIV').css('display', 'none');
                });
            }
        });

    });




 

    //##### details order overzicht ######//
    var el;
    var gdata;



    $('.show_details').mouseenter(function (e) {
        $('#hover').html("<img src=\"/images/ajax-loader.gif\">");
        $('#hover').css({
            'display': 'block',
            'top': e.pageY,
            'left': e.pageX
        });

        if (el != $(this).attr('id')) {
            el = $(this).attr('id');

            $.ajax({
                url: "/inloggen/details_orders.aspx?id=" + el,
                success: function (data) {
                    $('#hover').html(data);
                    gdata = data;
                }
            });
        }
        else {
            $('#hover').html(gdata);
        }
    });

    $('.show_details').mouseout(function (e) {
        $('#hover').css({
            'display': 'none',
            'top': e.pageY,
            'left': e.pageX
        });
    });

    // Select -> Company || Costumer		
    if ($('#type').length > 0) {
        $('#type').change(function () {
            if ($(this).val() == "Bedrijf") {
                $('#company').css('display', 'inline');
            }
            else {
                $('#company').css('display', 'none');
            }
        });
    }

    if ($('#vakgroep').length > 0) {
        $('#vakgroep').change(function () {
            if ($(this).val() == "Fotowinkel") {
                $('#subvakgroep').css('display', 'inline');
            }
            else {
                $('#subvakgroep').css('display', 'none');
            }
        });
    }

    // Filter 
    $('#filterList > ul > li').click(function (e) {
        var ul = $(this).find("ul");

        // Close other
        $.each($(this).parent().find("ul"), function (index, value) {
            $(value).css('display', 'none');
        });

        $(this).mouseleave(function (e) {
            ul.css('display', 'none');
        });

        if (ul.css('display') == "block") {
            ul.css('display', 'none')
        }
        else {
            ul.css('display', 'block')
        }
    });

    $('.relevant_click').click(function (e) {
        $('#relevant').css("display", "block");
        $('#specificaties').css("display", "none");
		$('#merk').css("display", "none");
        $('.relevant_click').addClass("selected");
        $('.specificaties_click').removeClass("selected");
		$('.merk_click').removeClass("selected");
    });

    $('.specificaties_click').click(function (e) {
        $('#relevant').css("display", "none");
        $('#specificaties').css("display", "block");
		$('#merk').css("display", "none");
        $('.relevant_click').removeClass("selected");
        $('.specificaties_click').addClass("selected");
		$('.merk_click').removeClass("selected");
    });
	$('.merk_click').click(function (e) {
        $('#relevant').css("display", "none");
        $('#specificaties').css("display", "none");
		$('#merk').css("display", "block");
        $('.relevant_click').removeClass("selected");
        $('.specificaties_click').removeClass("selected");
		$('.merk_click').addClass("selected");
    });

    var loadSelect = function (from) {
        // Query
        var q = new $.Hashtable();
        var tmp;
        var id = ""
        var sql = "";
        var load = true
		
		$.each($('#filterList').find("li"), function (i, v) {
			$(v).removeClass("filtered");
		});

        $.each($('#filterList').find("input:checked"), function (i, v) {
            id = $(v).attr("id").split(":");
			
			$(v).parent().parent().parent().addClass("filtered");

            if (false == q.containsKey(id[1])) q.add(id[1], id[2]);
            else {
                tmp = q.get(id[1]);
                q.remove(id[1]);
                q.add(id[1], tmp + "," + id[2]);
            }

            load = true
        });

        // Loop through hashtable
        for (var i in q.items) {
            sql = sql + i + "-" + q.items[i] + ";";
        }

        sql = sql.substr(0, sql.length - 1);
		
        if (false != load) {		
            // Ajax
            var ajax = $('#ajaxDiv');
            ajax.html("");
            $('#loader').css("display", "block");
			
			//alert("/webshop_filter.aspx?weergave=" + ajax.attr("class") + "&from=" + from + "&to=" + $('#aantal').val() + "&json=" + sql + "&aantal=" + $('#aantal').val() + "&categorie=" + encodeURIComponent($('.wLeft').text()) + "&rand=" + Math.random() * 100000);
			
			            
			$.ajax({
                url: "/webshop_filter.aspx?weergave=" + ajax.attr("class") + "&from=" + from + "&to=" + $('#aantal').val() + "&json=" + sql + "&aantal=" + $('#aantal').val() + "&categorie=" + encodeURIComponent($('.wLeft').text()) + "&rand=" + Math.random() * 100000,
                success: function (data) {
                    ajax.html(data);
                    $('#loader').css("display", "none");
				
					$('.pagina-nummers a').click(function (e) {
                        var page = $(this).attr("title");
                        loadSelect(page - 1)
                    });
					
					$('#first').click(function(e) {						
                        loadSelect(0)
					});
					
					$('#back').click(function(e) {
                        loadSelect($(this).attr("title"))
					});
					
					$('#last').click(function(e) {						
                        loadSelect(parseInt($(this).attr("title")) - 1);
					});
										
					$('#foreward').click(function(e) {
                        loadSelect($(this).attr("title"));
					});
					
					addActionsToView();
                }
            });
        }
    }

    if ($('#filterList').length > 0) loadSelect(0);

    $('#filterList > ul > li > ul > li > input').click(function (e) {
        loadSelect(0);
    });

    /* lijst weergave van producten */
    $('#weergave').change(function () {
        $("#frmweergave").submit();
    });

    $('#sorteren').change(function () {
        $("#frmweergave").submit();
    });

    $('#aantal').change(function () {
        //$("#frmweergave").submit();
		loadSelect(0); //aantal wijzigen met behoud filter
    });
	
	$('.foto-weergave').click(function(){
		$("#ajaxDiv").attr("class",$(this).attr("alt")); //change class
		
		//replace current image & other
		$('.foto-weergave').each(function(index, value){
			$(this).attr("src", $(this).attr("src").replace("weergave-over", "weergave"));
		});
		$(this).attr("src", $(this).attr("src").replace("weergave", "weergave-over"));
		//removeClass($("#ajaxDiv").attr("class")).addClass($(this).attr("alt"));
		loadSelect(0);
	});

    $("#fotos .small").mouseover(function () {
		$(".mainURL").attr({
            href: this.src.replace("-custom-", "-full-").replace("-random-", "-full-").replace("-medium-", "-full-")
        });

        $(".mainImage").attr({
            src: this.src.replace("-full-", "-custom-").replace("-random-", "-custom-")
        });

        $(this).attr({
            style: 'border: 1px solid #000000; margin: 3px; width: 42px; height: 42px;'
        });
    });

    $("#fotos .small").mouseout(function () {
        $(this).attr({
            style: 'border: 1px solid #CCCCCC; margin: 3px; width: 42px; height: 42px;'
        });
    });


    /* popup */
    var $info = ""
    $('.infoicon').hover(
		function (e) {
		    $info = $(this).attr("title");
		    $(this).attr("title", "")

		    var $div = $("<div></div>").attr("id", "infodiv").css("left", e.pageX + 5).css("top", e.pageY + 5);
		    $("<span class=\"infotitle\">" + $info.split("::")[0] + "</span>").appendTo($div)
		    $("<span class=\"contents\">" + $info.split("::")[1] + "</span>").appendTo($div);

		    $('#container').append($div)

		    if ($(window).height() <= ((e.pageY + 5) - $(window).scrollTop()) + $div.height())
		        $div.css("top", e.pageY - $div.height());

		}, function (e) { $('#infodiv').remove(); $(this).attr("title", $info); }
	);

    //toggle show/hide
    $(".toggle").click(function (e) {
        var ids = $(this).attr("id").split("_")
        var id = ids[1]
        $("#slidingDiv_" + id).animate({ "height": "toggle" }, { duration: 250 });
    });
	
	addActionsToView();
	
	fix_flash();
	
});

function addActionsToView() {
    $('.aantal').focus(function (e) {
        if ($(this).val() == "1")
            $(this).val("");
    });

    $('.aantal').blur(function (e) {
        if ($(this).val() == "")
            $(this).val("1");
    });
	
	   //##### Order multiple ######//
    $('.additem').click(function (e) { // on click
        var $input = $($(this).parent().parent().children("td")[5]).contents("input"); // Get input
        if (parseInt($input.val()) != "NaN") $input.val(parseInt($input.val()) + 1); // Count +1 if input is an number
    }); // Close AddItem

    $('.removeitem').click(function (e) { // on click
        var $input = $($(this).parent().parent().children("td")[5]).contents("input"); // Get input
        if (parseInt($input.val()) != "NaN" && parseInt($input.val()) > 0) $input.val(parseInt($input.val()) - 1); // Count +1 if input is an number and > 0
    }); // Close AddItem
	
	$(".txtAdd").bind("keydown", function (e) {
        if (e.keyCode == 38) {
			if (parseInt($(this).val()) != "NaN") $(this).val(parseInt($(this).val()) + 1);
        }
        else if (e.keyCode == 40) {
			if (parseInt($(this).val()) != "NaN" && parseInt($(this).val()) > 0) $(this).val(parseInt($(this).val()) - 1);
        }
    }).change();
	
    $('#divsuggestions > img').click(function (e) {
        $(this).parent().remove();
        createCookie("suggestion", "x")
    });
	
	$('#melding > img').click(function (e) {
        $(this).parent().remove();
        createCookie("melding", "x")
    });
}

function fix_flash() {
    // loop through every embed tag on the site
    var embeds = document.getElementsByTagName('embed');
    for (i = 0; i < embeds.length; i++) {
        embed = embeds[i];
        var new_embed;
        // everything but Firefox & Konqueror
        if (embed.outerHTML) {
            var html = embed.outerHTML;
            // replace an existing wmode parameter
            if (html.match(/wmode\s*=\s*('|")[a-zA-Z]+('|")/i))
                new_embed = html.replace(/wmode\s*=\s*('|")window('|")/i, "wmode='transparent'");
            // add a new wmode parameter
            else
                new_embed = html.replace(/<embed\s/i, "<embed wmode='transparent' ");
            // replace the old embed object with the fixed version
            embed.insertAdjacentHTML('beforeBegin', new_embed);
            embed.parentNode.removeChild(embed);
        } else {
            // cloneNode is buggy in some versions of Safari & Opera, but works fine in FF
            new_embed = embed.cloneNode(true);
            if (!new_embed.getAttribute('wmode') || new_embed.getAttribute('wmode').toLowerCase() == 'window')
                new_embed.setAttribute('wmode', 'transparent');
            embed.parentNode.replaceChild(new_embed, embed);
        }
    }
    // loop through every object tag on the site
    var objects = document.getElementsByTagName('object');
    for (i = 0; i < objects.length; i++) {
        object = objects[i];
        var new_object;
        // object is an IE specific tag so we can use outerHTML here
        if (object.outerHTML) {
            var html = object.outerHTML;
            // replace an existing wmode parameter
            if (html.match(/<param\s+name\s*=\s*('|")wmode('|")\s+value\s*=\s*('|")[a-zA-Z]+('|")\s*\/?\>/i))
                new_object = html.replace(/<param\s+name\s*=\s*('|")wmode('|")\s+value\s*=\s*('|")window('|")\s*\/?\>/i, "<param name='wmode' value='transparent' />");
            // add a new wmode parameter
            else
                new_object = html.replace(/<\/object\>/i, "<param name='wmode' value='transparent' />\n</object>");
            // loop through each of the param tags
            var children = object.childNodes;
            for (j = 0; j < children.length; j++) {
                try {
                    if (children[j] != null) {
                        var theName = children[j].getAttribute('name');
                        if (theName != null && theName.match(/flashvars/i)) {
                            new_object = new_object.replace(/<param\s+name\s*=\s*('|")flashvars('|")\s+value\s*=\s*('|")[^'"]*('|")\s*\/?\>/i, "<param name='flashvars' value='" + children[j].getAttribute('value') + "' />");
                        }
                    }
                }
                catch (err) {
                }
            }
            // replace the old embed object with the fixed versiony
            object.insertAdjacentHTML('beforeBegin', new_object);
            object.parentNode.removeChild(object);
        }
    }
}

