﻿var trace = null;//$(".debug-trace");

function SubMenu(parent) {
    var self = this;
    var timer = null;
    var menu = null;
    
    // show the menu
    this.show = function() {        
        menu.fadeIn('fast');
    }

    // hide the menu
    this.hide = function() {
        menu.fadeOut('fast');
    }

    // all the bindings
    this.bindings = function() {
        parent.bind('mouseenter', function() {
            self.show();
            parent.addClass('hover');
            clearTimeout(timer);
        });

        parent.bind('mouseleave', function() {
            timer = setTimeout((function() {
                self.hide();
                parent.removeClass('hover');
            }), 150);
        });

        menu.bind('mouseenter', function() {
            self.show();
            parent.addClass('hover');
            clearTimeout(timer);
        });

        menu.bind('mouseleave', function() {
            self.hide();
            parent.removeClass('hover');
        });
    }

    this.init = function() {
        // find the sub menu or end
        if ($(".sub-menu[rel='" + parent.attr('id') + "']").length) {
            menu = $(".sub-menu[rel='" + parent.attr('id') + "']");
        } else {
            return false;
        }

        // set the menu position
        menu.css('left', parent.position().left);

        this.bindings();
    }

    this.init();
}

function init_submenus() {
    $("#nav .menu li a").each(function(e) {
        new SubMenu( $(this) );
    });
}

function search_box() {
    var box = $(".search");
    if (!box.val()) {
        box.val('Indtast søgeord').css({ color: '#777', fontStyle: 'italic' });
        
        box.bind('focus', function() {
            if (box.val() == 'Indtast søgeord') {
                box.val('').css({ color: '#333', fontStyle: 'normal' });
            }
        });

        box.bind('blur', function() {
            if (box.val() == '') {
                box.val('Indtast søgeord').css({ color: '#777', fontStyle: 'italic' });
            }
        });

        box.bind('keypress', function(e) {
            if (e.keyCode == 13) {
                window.location.href = "/pages/search.aspx?GUID=118&q=" + box.val();
                return false;
            }
            
        });
    }

    $(".srcButton").bind('click', function() {
    window.location.href = "/pages/search.aspx?GUID=118&q=" + box.val();
    });
}

function input_ghost() {
    $(".ghost").each(function() {

        if (!$(this).val()) { $(this).val($(this).attr('title')); }

        $(this).bind('focus', function() {
            if ($(this).val() == $(this).attr('title')) {
                $(this).val('').removeClass('ghost');
            }

            if ($(this).attr('id') == 'login_password') {
                $(this).get(0).setAttribute('type', 'password');
            }
        });

        $(this).bind('blur', function() {
            if ($(this).val() == '') {
                $(this).val($(this).attr('title')).addClass('ghost');

                if ($(this).attr('id') == 'login_password') {
                    $(this).get(0).setAttribute('type', 'text');
                }
            }              
        });

    });
}

function enableQuickMenu() {
    $(".quickMenu").change(function() {
        window.location.href = $(this).val();
    });
}

function imageBrowser() {
    $(".image .gallery li img").click(function() {
        img = $(this).attr('src').replace('small', 'full');
        $(".preview").fadeOut('fast', function() {
            $(this).attr('src', img);
            $(this).fadeIn('fast');
        });

        $(".image .gallery li img").removeClass("active")
        $(this).addClass("active")
    });
}

function product_image_browser() {
    if ($(".gallery li").length > 0) {
        
        // add a frame to the first thumbnail
        $(".gallery li:first-child").addClass("active");

        // make thumbnails clickable
        $(".gallery li img").click(function() {
            var self = this;

            $(".gallery li").removeClass('active');
            $(self).parent().addClass('active');

            var src = $(self).attr('src')

            $("#ctl00_cphPage_imgProduct").fadeOut('fast', function() {
                $(this).attr('src', src.replace('small', 'full'));
                $(this).parent().attr('href', $(this).attr('src'));
                $(this).fadeIn();
            });
        });
    }
}

$.basket = {
    add: function(sender) {
    	/*
        $.ajax({
            type: 'GET',
            url: '/controls/basket.ashx',
            data: 'GUID=PASSED&action=addItem&pid=' + $("#ctl00_cphPage_lblPartNumber").text() + '&amount=' + $("#amount").val() + '&price=' + $("#ctl00_cphPage_lblPrice").text().replace('DKK ', ''),
            beforeSend: function() {
                $(sender).html("Tilføjer")
            },
            success: function(response) {
                $("#basketAmount").html(response);
                $.account.basket.render();
                $(sender).html("Læg i kurv");
                
                // tell google someone put something in the basket
				if (_gaq) { 
					var lbl = 'varenr: '+ $("#ctl00_cphPage_lblPartNumber").text() +', antal: ' + $("#amount").val();
					_gaq.push(['_trackEvent', 'Kurven', 'Vare tilføjet', lbl, $("#ctl00_cphPage_lblPrice").text().replace('DKK ', '')]);
				}
            }
        });
*/
        return false;
    }
}

$.account = {

    state: 'closed',

    init: function() {
        var cls = this;
        $("#login_submit").click(function() { $.account.login(); return false; });
        $("#user-account-button.clickable").bind('click', function() {
            if (!$(".account-products").length) {
                if (cls.state == 'closed') {
                    cls.show(); cls.state = 'open';
                } else {
                    cls.hide(); cls.state = 'closed';
                }
            }
        });

        cls.order.render();
    },

    show: function() {
        $("#user-account").animate({ top: 0 }, 'normal');
        $(document.body).animate({ marginTop: 100 }, 'normal');
        $("#login_username").focus();
    },

    hide: function() {
        $("#user-account").animate({ top: -95 }, 'normal');
        $(document.body).animate({ marginTop: 0 }, 'normal');
    },

    login: function() {
        var user = $("#login_username").val();
        var pass = $("#login_password").val();
        var is_valid = true;
		
		// tell google someone tries to login
		if (_gaq) { 
			_gaq.push(['_trackEvent', 'Logind', 'Loginforsøg', $("#login_username").val(), 10]);
		}

        // check to see if the items are filled
        if (!user) {
            $("#login_username").addClass('missing-input').focus();
            return false;
        }

        if (!pass) {
            $("#login_password").addClass('missing-input').focus();
            return false;
        }

        // remove the extra classes
        $("#login_password,#login_username").removeClass('missing-input');

        // disable the submit while we test the credentials
        $("#login_submit").fadeTo('fast', 0.5).unbind('click').html('Logger ind...');

        $.ajax({
            type: 'POST',
            url: '/controls/login.ashx?GUID=PASSED',
            data: 'username=' + user + '&password=' + pass + '',
            onFailure: function() {
            	// tell google login failed
				if (_gaq) { 
					_gaq.push(['_trackEvent', 'Logind', 'Mislykket logind forsøg', user, 0]);
				}
                alert('Der forekom en fejl. Prøv igen senere');
            },
            success: function(response) {
                if (response == 'True') {
                	// tell google someone tries to login
					if (_gaq) { 
						_gaq.push(['_trackEvent', 'Logind', 'Logget ind', user, 100]);
					}
                    window.location = window.location;
                } else {
                    $("#login_submit").fadeTo('fast', 1).bind('click', function() { $.account.login(); }).html('Logind');
                    $("#login_submit").unbind('click', null).click(function() { $.account.login(); return false; });
                    alert("Brugernavn eller password kunne ikke findes i databasen");
                }
            }
        });
    },

    basket: {
        render: function() {
        	/*
            $.ajax({
                type: 'GET',
                url: '/controls/	',
                data: 'guid=passed&action=renderBasket',
                beforeSend: function() { $(".account-products").html('<div class="basket-notice">Vent mens kurven bliver opdateret</div>'); },
                success: function(response) {
                    $(".account-products").html(response);
                }
            })
            */
        },

        update: function(uid, amount, sender) {
        	/*
            $.ajax({
                type: 'GET', url: '/controls/basket.ashx', data: 'guid=passed&action=update&uid=' + uid + '&amount=' + amount,
                beforeSend: function() {
                    sender.fadeTo('fast', 0.5);
                },
                success: function() {
                    sender.fadeTo('fast', 1);
                }
            })
            */
        }
    },

    order: {

        render: function() {
            // if we are not on the order page we should quit
            if (!$(".order-table").length) { return false }

            // bind the updater
            $(".order-table .item").each(function(i, el) {
                // get the elements
                var pid = $(el).attr('id');
                var info = $(el).children('.info');
                var price = $(el).children('.p-price').val();
                var amount = $(el).children('.info').children('.amount').children('input');
                var prev_amount = amount.val();
                var totalPrice = info.children('.total_price');

                // get the price
                //var price = $(el).next();
                var timer = null;

                // bind the amount
                amount.bind('keyup', function() {
                    // clear the timer
                    clearTimeout(timer);
                    timer = null;

                    // save the el
                    var el = $(this);

                    // get the vars
                    timer = setTimeout(function() {
                        var quantity = el.val();
                        var total = parseFloat(price) * quantity;
                        var uid = el.attr('rel');

                        totalPrice.html('kr. ' + addCommas(total.toFixed(2)));
                        $.account.basket.update(uid, quantity, el.parent().parent().parent());
                    }, 300);
                });
            });

            // bind the remove
            $(".remove_product").bind('click', function() {
                var uid = $(this).attr('rel');
                var parent = $(this).parent().parent();

                // make the changes
                $.ajax({
                    type: 'GET', url: '/controls/basket.ashx', data: 'guid=passed&action=remItem&uid=' + uid,
                    beforeSend: function() {
                        parent.fadeTo('slow', 0.5);
                    },
                    success: function(response) {
                        parent.animate({ 'height': 0, 'padding': 0, 'margin': 0 }, 'slow', function() {
                            parent.remove();
                        });
                    }
                })
            });
        }

    }
}

$.product = {

    bindEvents: function() {
        // the add to basket
        $(".add-to-basket").removeAttr('onclick').click(function() {
            var btn = $(this);

            // create the params
            var itemNumber = $("#ctl00_cphPage_lblPartNumber").text().replace('DKK ', '');
            var amount = $("#amount").val();
            var price = $("#ctl00_cphPage_lblPrice").text().replace('DKK ', '');
            var variation = '';
            
            var complete = true;

            // get the variations
            $(".variationlist").each(function(i, el) {
                if (el.selectedIndex == 0) {
                    alert(el.options[0].text);
                    complete = false;
                }

                var name = el.options[0].text.split(" ")[1] + ': ';
                variation += (variation ? ',' : '') + name + escape(el.options[el.selectedIndex].text);
            });
            
            if ( !complete ) {
            	return false;
            }

            // send the request
            $.ajax({
                type: 'GET', url: '/controls/basket.ashx',
                data: 'GUID=PASSED&action=addItem&pid=' + itemNumber + '&amount=' + amount + '&price=' + price + '&variation=' + variation,
                beforeSend: function() {
                    btn.html("Tilføjer");
                },
                error: function() {
                    //alert("Der forekom en fejl")
                },
                success: function(response) {
                    $("#basketAmount").html(response);
                    $.account.basket.render();
                    btn.html("Læg i kurv");
                    
                    if (_gaq) { 
						var lbl = 'varenr: '+ itemNumber +', antal: ' + amount;
						_gaq.push(['_trackEvent', 'Kurven', 'Vare tilføjet', lbl, price]);
					}
                }
            });
        });

        // bind dropevents       
        $(".variationlist").each(function(i, el) {
            var dropdown = $(this);
            dropdown.bind('change', function() {
                var itm = this.options[this.selectedIndex].value;
                                
                // bind image event
                if (itm.indexOf('img:') == 0) {
                    var img = $("#ctl00_cphPage_parentProduct").text() + '_' + itm.replace('img:', '').toUpperCase() + '.jpg';

                    $(".gallery li img").each(function(i, el) {
                        if ($(el).attr('src').indexOf(img) > 0) {
                            $(el).click();
                        }
                    });
                }

                // bind prod event
                if (itm.indexOf('prod:') == 0) {
                    //var prod = 'produkt/' + itm.replace('prod:', '') + '.aspx';
                    //console.log(prod);
                }
            });
        });
    },

    init: function() {
        if (!$(".product").length) {
            return false;
        }

        //this.bindEvents();
    }

}

var application = function() {

    var inst = this;

    this.validate = function() {
        var isValid = true;

        $("#login_application input[rel='required']").each(function(i, el) {
            if (!$(el).val()) {
                isValid = false;
                $(el).css('background', 'lightyellow');
            } else { $(el).css('background', 'white'); }
        });

        $("#login_application input[reg]").each(function(i, el) {
            var pattern = '';

            switch ($(el).attr('reg')) {
                case 'number':
                    pattern = /^(\d+)$/g;
                    break;
                case 'phone':
                    pattern = /^[\d]{8,12}$/g;
                    break;
                case 'email':
                    pattern = /\b[\w\.-]+@[\w\.-]+\.\w{2,4}\b/g;
                    break;
            }

            if (!$(el).val().match(pattern)) {
                isValid = false;
                $(el).css('background', 'lightyellow');
            } else { $(el).css('background', 'white'); }
        });

        return isValid;
    }

    if ($("#login_application").length) {

        $("#login_application input[rel='required']").bind('blur', function() {
            if (inst.validate()) {
                $("#ctl00_cphPage_btnSendApplication").removeAttr('disabled').fadeTo('fast', 1);
            } else {
            $("#ctl00_cphPage_btnSendApplication").attr('disabled', 'disabled').fadeTo('fast', 0.5);
            }
        });

        $("#ctl00_cphPage_btnSendApplication").attr('disabled', 'disabled').css('opacity', 0.5);
    }

}

$(document).ready(function() {
    $.product.init();

    init_submenus();
    search_box();
    enableQuickMenu();
    //imageBrowser();
    product_image_browser();
    input_ghost();

    application();

    // the account thingy
    $.account.init();
    //$.account.basket.render();

    // update hte form
    var url = window.location.href
    $("#aspnetForm").attr('action', url);
});

$(function() {
    $('a[rel*=lightbox],a.lightbox').lightBox({
        imageLoading: '/layout/images/lightbox-ico-loading.gif', 	// (string) Path and the name of the loading icon
        imageBtnPrev: '/layout/images/lightbox-btn-prev.gif', 		// (string) Path and the name of the prev button image
        imageBtnNext: '/layout/images/lightbox-btn-next.gif', 		// (string) Path and the name of the next button image
        imageBtnClose: '/layout/images/lightbox-btn-close.gif', 	// (string) Path and the name of the close btn
        imageBlank: '/layout/images/lightbox-blank.gif',
        overlayOpacity: 0.45
    });
});

function addCommas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? ',' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + '.' + '$2');
	}
	return x1 + x2;
}
