/* globals */
slideshow_html = '';
currentslide = 0;
totalslides = 0;
slideshow = '';
screenwidth = getScreenWidth();
screenwidth_larger = getScreenWidth(true);
thumb_offsets = [];
thumb_widths = [];
thumbbar_width = 0;
thumbslider = '';
scrollbarwidth = 0;
lastaction = 'slideshow';

$(window).resize(function() {
    screenwidth = getScreenWidth();
});

$(function() {

    //setInterval(function(){ vp=getViewport();$(".wrapper").html('<h1 style="color:red">width: '+vp['viewportwidth']+'<br/>height:'+vp['viewportheight']+'</h1>') },300);
    $("a,area,map,object,input[type=submit]").bind("focus", function() {
        if ($(this).blur)$(this).blur();
    });

    function overlabel() {
        $(".overlabel").each(function() {
            if ($(this).val() == '') {
                $(this).val($(this).attr("title")).addClass('overlabel_inactief');
            }
        });
        $(".overlabel").focus(function() {
            if ($(this).val() == $(this).attr("title")) {
                $(this).val('').removeClass('overlabel_inactief');
            }
        });
        $(".overlabel").blur(function() {
            if ($(this).val() == '') {
                $(this).val($(this).attr("title")).addClass('overlabel_inactief');
            }
        });
    }

    overlabel();

    if ($("#flashvideo").length > 0) {
        src = $("#flashvideo").attr("rel");
        swfobject.embedSWF(src + ".swf", "flashvideo", screen.width, screen.height, "9.0.0", "", {}, {
            allowScriptAccess: "always",
            wmode: "transparent"
        });
    }

    if ($("body.about").length > 0) {
        $("body").css("background", "url('/gfx/background/" + screenwidth_larger + "/about.jpg') center no-repeat");
    }
    if ($("body.contact").length > 0) {
        $("body").css("background", "url('/gfx/background/" + screenwidth_larger + "/contact.jpg') center no-repeat");
    }


    if ($("body.stock-view").length > 0) {
        $(window).resize(function() {
            update_stock_viewport();
        });
        update_stock_viewport();
    }

    if ($("#slideshow_src").length > 0) {
        $(window).resize(function() {
            init_slideshow();
        });
        init_slideshow();
        setInterval('checkSliderStatus()', 800);
    }

    $("a.logo").click(function() {
        ml = 0;
        easing = 'linear';
        //topmenu_slide(1);
    });
    /*
     $("ul.menu a[href!='#']").click(function(){
     topmenu_slide(1);
     setTimeout('document.location=\''+$(this).attr("href")+'\'',1000);
     return false;
     })
     */
    //    $("body.homepage a.logo").trigger("click");

    function topmenu_slide() {
        return false;
        if ($("ul.menu").hasClass('animate')) return false;

        if ($("ul.menu>li:first-child").css("margin-left") == '-200px') {
            easing = 'easeInOutBack';
            duration = 800;
            $("ul.menu").addClass('animate');
            $("ul.menu>li").each(function() {
                destination_left = $(this).attr("rel");
                duration = duration + 150;
                $(this).stop().animate({
                    marginLeft:destination_left + 'px'
                }, duration, easing, function() {
                    $("ul.menu").removeClass('animate');
                });
            });
        } else {
            easing = 'easeInOutBack';
            duration = 800;
            $("ul.menu").addClass('animate');
            $("ul.menu>li").each(function() {
                destination_left = $(this).attr("rel");
                duration = duration + 150;
                $(this).stop().animate({
                    marginLeft:'-200px'
                }, duration, easing, function() {
                    $("ul.menu").removeClass('animate');
                });
            });
        }
    }


    $("ul.menu>li.sub").hover(function() {
        $(this).children("ul").css('top', '60px');
    }, function() {
        $(this).children("ul").css('top', '-1000px');
    });

    $("ul.menu>li.sub").click(function() {

        $("ul.menu>li.sub ul").css('top', '60px');
    })

    $("div.thumbs_bottom>.tabhandle").click(function() {
        if ($("div.thumbs_bottom").hasClass("up")) {
            switch_bottomthumbs('collapse');
        }
        else {
            switch_bottomthumbs('expand');
        }
        return false;
    })

    $("div.bottomblock").click(function() {
        switch_bottomblock('expand');
    });

    $("div.bottomblock a.collapse").click(function() {
        switch_bottomblock('collapse');
    });

    $("div.bottomblock>ul.tabs>li").click(function() {
        if (!$(this).hasClass('selected')) {
            var selected_nr = $(this).attr("class").split(' ')[0].split('tab')[1];

            $("div.bottomblock>ul.tabcontent>li").removeClass("selected");
            $("div.bottomblock>ul.tabcontent>li.tab" + selected_nr).addClass("selected");
            $("div.bottomblock>ul.tabs>li").removeClass("selected");
            $(this).addClass('selected');
        }
        else {
            switch_bottomblock('collapse');
        }
    });

    $("div.overlay.clear").click(function() {
        switch_bottomblock('collapse');
        $("div.overlay.clear").hide();
    });

    $("form.search_stock").submit(function() {
        if (($(this).children("input[type=text]").val()) == ($(this).children("input[type=text]").attr("title"))) {
            $(this).children("input[type=text]").val('');
        }
    });

    $(".a_form").submit(function() {
        this_id = $(this).attr("id");

        if ($("#" + this_id).hasClass('form_submitting')) {
            return false;
        }
        $(this).addClass('form_submitting');

        $('#' + this_id + '.overlabel_inactief').val('');

        // tinymce
        if (typeof tinyMCE != "undefined") {
            tinyMCE.triggerSave(true, true);
        }
        val = $(this).serialize();
        $('.overlabel_inactief').trigger('blur');

        // loading(1);
        $.post("/ajax/forms.php", {
            form:this_id,
            val:val
        }, function(data) {
            // loading();
            $("#" + this_id).removeClass('form_submitting');
            errors = data.error;
            ok_red = data.ok_red;
            ok_func = data.ok_func;
            error_text = '';

            if (errors) {
                if (errors.length > 1) {
                    error_text = '\n - ';
                }
                error_text += errors.join('\n - ');

                alert('We could not process your message:' + error_text);
                $("#" + this_id).removeClass('form_submitting');
                return false;
            }
            else {
                try {
                    if (ok_red) {
                        loading();
                        window.location = ok_red;
                        return false;
                    }
                    // if (ok_red) { return false; }
                    if (ok_func) {
                        eval(ok_func);
                        loading();
                        return false;
                    }
                }
                catch(err) {
                }
            }

            error_text = 'Something went wrong, try again later';

        }, "json");
        $("#" + this_id).removeClass('form_submitting');
        return false;
    });

    $(".a_submit").click(function() {
        $(this).parents('.a_form').submit();
        return false;
    });

    $(".search_stock").submit(function() {
        action = $(this).attr("action");
        search = escape($(this).children("input[name='search']").val());

        document.location = action + search;
        return false;
    })

    //get hash from url
    getUrl();
});


function switch_bottomblock(action) {
    is_expanded = ($("div.bottomblock").css("bottom").split('px')[0] == 0);


    if (action == 'expand' && !is_expanded) {
        $("div.bottomblock .submitted").hide();

        $("div.overlay.clear").show();
        $("div.bottomblock").animate({
            bottom:'0px'
        }, 1000, 'easeInBack', function() {
            $("div.overlay.clear").show();
        });
    }

    if (action == 'collapse' && is_expanded) {
        $("div.bottomblock").animate({
            bottom:'-450px'
        }, 1000, 'easeOutCirc', function() {

        });
    }
}

function stock_form_reset() {
    $(".bottomblock .submitted").fadeIn();
    $(".bottomblock .a_form")[0].reset();

}

function switch_bottomthumbs(action) {
    is_expanded = ($("div.thumbs_bottom").css("bottom").split('px')[0] == 0);
    cur_rel = $("#slideshow_src .subject").attr("rel").split(",");

    if (action == 'expand' && !is_expanded) {
        $("div.thumbs_bottom").animate({
            bottom:'0px'
        }, 1000, 'easeInBack', function() {
            $("div.thumbs_bottom").removeClass('down').addClass('up');
            $("#slideshow_src .subject").attr("rel", cur_rel[0] + "," + cur_rel[1] + ",250");
            init_slideshow();
        });

    }
    if (action == 'collapse' && is_expanded) {
        $("div.thumbs_bottom").animate({
            bottom:'-101px'
        }, 1000, 'easeOutCirc', function() {
            $("div.thumbs_bottom").removeClass('up').addClass('down');
            $("#slideshow_src .subject").attr("rel", cur_rel[0] + "," + cur_rel[1] + ",100");
            init_slideshow();
        });

    }
}


function init_slideshow() {
    //store status
    slideshow = '';
    slideshow_html = $("#slideshow_src").html();
    $("#slideshow_wrapper").html(slideshow_html);
    $("#slideshow_wrapper .subject").attr("id", "slideshow");

    orig_size = $("#slideshow").attr("rel").split(',');
    orig_width = orig_size[0];
    orig_height = orig_size[1];
    orig_ratio = orig_width / orig_height;
    orig_horizontal = (orig_ratio > 1);
    offset_y = orig_size[2];

    size = getViewport();

    max_width = size['viewportwidth'];
    max_height = size['viewportheight'] - offset_y;
    orig_ratio = orig_width / orig_height;
    max_ratio = max_width / max_height;
    totalslides = $("#slideshow .slide").size();

    diff_width = max_width - orig_width;
    diff_height = max_height - orig_height;

    if ((diff_width) <= (diff_height)) { //limit width
        slide_height = Math.round(max_width / orig_ratio);
        slide_width = max_width;
        $("#slideshow .slide,.slidewrap").css("height", slide_height + 'px');
        $("#slideshow .slide img").css('max-width', '98%');

    } else {
        slide_width = Math.round(max_height * orig_ratio);
        slide_height = max_height;
        $("#slideshow .slide,.slidewrap").css("height", slide_height + 'px');
        $("#slideshow .slide img").css("height", slide_height + 'px');

    }
    $("#slideshow,#slideshow .slide").css('height', slide_height + 'px');
    //$("#slideshow .slide img").css('max-height',slide_height+'px');
    //$("#slideshow .slide img").css('max-width',slide_width-30+'px');
    margin_left = Math.round((max_width - slide_width) / 2);
    $("#slideshow,#slideshow .slide").css("width", max_width + 'px');
    // $("#slideshow .slidewrap").css("width",slide_width+'px').css('margin-left',margin_left+'px');

    handle_width = totalslides * max_width;
    $("#slideshow .handle").css("width", handle_width + 'px');

    slideshow = new Dragdealer('slideshow', {
        steps: totalslides,
        speed: 50,
        loose: true
    });

    if (currentslide > 0) {
        slideshow.setStep(currentslide + 1);
    }

    //  $("#slideshow").css('height',slide_height+'px')
    //this_width = $("#slideshow .slide img").clientWidth(); 
    //alert(this_width)

    $("a.arrow").click(function() {

        if ($(this).hasClass('prev')) {
            slideshow.setStep(currentslide);
        }
        if ($(this).hasClass('next')) {
            slideshow.setStep(currentslide + 2);

        }
    });

    thumbnailbar_init();
    checkSliderStatus();
    loadSlideImages();
}


/* checks every second which image is being displayed and sets the right SRC based on the screen resolution */
function loadSlideImages() {
    i = 0;

    $("#slideshow .slide img").each(function() {
        nr = $(this).attr("class").split("nr")[1];
        if ((nr == currentslide - 1) || (nr == currentslide) || (nr == currentslide + 1) || (nr == currentslide + 2)) {
            preloadSlideImage(nr);
        }
        else {
            $(this).attr("src", "");
        }
    });
}

function preloadSlideImage(nr) {
    obj = $("#slideshow .slide img.nr" + nr);
    res = getScreenWidth();
    if (obj.attr("src") == "") {
        rel = obj.attr("rel").split('[res]').join(screenwidth);
        obj.attr("src", rel);
    }
}

//setInterval('loadSlideImages()',3000);

/* determines which image format to use based on the user screen resolution */
function getScreenWidth(larger) {
    widths = ['1024','1280','1680','1920','2560','3200','3200','3200'];
    for (i = 0; i < widths.length; i++) {
        if (widths[i] >= screen.width) {
            if (larger) {
                return widths[i + 2];
            }
            return widths[i];
        }
    }
    return widths[widths.length - 1];
}

/* determines the current slide the user is viewing, runs every second */
function checkSliderStatus() {
    left = $("#slideshow .handle").css("left").split("px")[0];
    slide_width = $("#slideshow").css("width").split("px")[0];
    slide_count = $("#slideshow li").size();
    slide = left / slide_width;
    slide = Math.round(slide) * -1;
    slide_nr = Math.round(slide);
    if (slide_nr != currentslide) {
        currentslide = slide_nr;

        loadSlideImages();
        if (lastaction == 'slideshow') {
            thumbnailbar_goto(currentslide);
        }
    }
}


function getUrl() {
    var hash = location.hash;
    if (!hash) {
        return false;
    }
    var photo_id = hash.split('-')[1];
    setTimeout(function(){$("#thumbs img[rel='" + photo_id + "']").trigger("click");},50);
}


function resize_maxdiv() {
    $("body").css("overflow", "hidden");
    if (!$("#vidplayer").length) {
        return false;
    }

    t = getViewport();
    viewportwidth = t.viewportwidth;
    viewportheight = t.viewportheight;
    aspectratio = 1.6;
    $("#maxdiv").css('width', viewportwidth + 'px');
    $("#maxdiv").css('height', viewportheight + 'px');

    if (viewportwidth > viewportheight) {
        width = viewportwidth * aspectratio
        height = viewportwidth;
        offsettop = (viewportheight - height) / 2;
        // $("#maxdiv").css('width',width+'px');
        //$("#maxdiv").css('height',height+'px');

        $("#maxdiv #vidplayer").css('height', '2000px');
        $("#maxdiv #vidplayer").css('width', '1300px');
        $("#maxdiv #vidplayer").css('top', '-700px');
    }
    else {
        $("#maxdiv").css('height', viewportheight + 'px');
        width = viewportheight * aspectratio;
        offsetleft = (viewportwidth - width) / 2;
        //$("#maxdiv #vidplayer").css('marginTop','0');
        $("#maxdiv #vidplayer").css('width', '2400px');
        $("#maxdiv #vidplayer").css('height', '1300px');
        $("#maxdiv #vidplayer").css('left', '-700px');
    }

    if ($("#vidplayer").length) {
        var pElement = document.getElementById("vidplayer");

        pElement.load();
        pElement.play();
    }

}
$(function() {
    if ($("#vidplayer").length) {
        $(window).resize(function() {
            window.location.reload();
        });
        resize_maxdiv();
    }
})

/* initialize the thumbnail bar, set right dimensions for thumbs and scroll, is loaded at pageload & resize */
function thumbnailbar_init() {
    thumbbar_width = 0;
    i = 0;
    $('#thumbs img').each(function() {
        i++;
        this_width = $(this).attr("width");
        thumbbar_width += this_width;
        thumb_offsets[i] = thumbbar_width; //distance to left from this thumb
        thumb_widths[i] = this_width;

        $(this).addClass('thumb-' + i);
    })
    t = getViewport();
    viewportwidth = t['viewportwidth'];

    $("#simple-slider").css("width", viewportwidth + "px");
    $("#thumbs").css("width", thumbbar_width + "px").css("left", 0);
    scrollbarwidth = Math.round((viewportwidth - thumbbar_width) / thumbbar_width * viewportwidth) * -1;
    $(".thumbs_bottom .scrollbar>.handle").css('width', scrollbarwidth + 'px').css('left', 0);

    thumbslider = new Dragdealer('simple-slider', {
        animationCallback: function(x) {
            thumbnailbar_scrollaction(x, viewportwidth - scrollbarwidth);
        }
    });
}

function thumbnailbar_scrollaction(x, leftwidth) {
    leftwidth = x * leftwidth;
    $(".thumbs_bottom .scrollbar>.handle").css('left', leftwidth + 'px');
}

/* center the thumbnailbar on a thumb that is currently viewed */
function thumbnailbar_goto(imgnr) {
    thumb_width = thumb_widths[imgnr];
    thumb_offset = thumb_offsets[imgnr];
    if (!thumb_width) return false;
    viewport = getViewport();
    viewportwidth = viewport['viewportwidth']

    half_screen_width = viewportwidth / 2;
    left = half_screen_width - thumb_offset - thumb_width;

    perc = (currentslide) / (totalslides);

    thumbslider.setValue(perc);
    leftwidth = perc * viewportwidth - scrollbarwidth;
    //console.log(perc);

    if (left > 0) left = 0;
    gap = viewportwidth - (thumbbar_width + left); //prevent gap on right side
    if (gap > 0) left = left + gap;

    return false;
}

$(function() {
    $('#thumbs img').bind("touchend click", function() {
        this_nr = $(this).attr("class").split("-")[1];
        //thumbnailbar_goto(this_nr);
        preloadSlideImage(this_nr);
        slideshow.setStep(this_nr);
    })
    $('#thumbs img').bind("touchstart mouseup", function() {
        lastaction = 'thumbbar';
    })
    $('#slideshow').bind("touchstart mouseup", function() {
        lastaction = 'slideshow';
    })
})


function getViewport() {
    var viewportwidth;
    var viewportheight;
    if (typeof window.innerWidth != 'undefined') {
        viewportwidth = window.innerWidth,
            viewportheight = window.innerHeight
    }
    else if (typeof document.documentElement != 'undefined'
        && typeof document.documentElement.clientWidth !=
        'undefined' && document.documentElement.clientWidth != 0) {
        viewportwidth = document.documentElement.clientWidth,
            viewportheight = document.documentElement.clientHeight
    }
    else {
        viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
            viewportheight = document.getElementsByTagName('body')[0].clientHeight
    }
    size = [];
    size['viewportwidth'] = viewportwidth;
    size['viewportheight'] = viewportheight;

    return size;
}

function update_stock_viewport() {
    viewport = getViewport();
    height = viewport['viewportheight'];
    width = viewport['viewportheight'];

    infobar_height = 130;//$("body.stock-view .imgwrap .info").height();
    available_height = height - infobar_height - 120;

    $(".stockimg").css("height", available_height + "px");
}


// Browser Detection
function css_browser_selector(u) {
    var ua = u.toLowerCase(),is = function(t) {
        return ua.indexOf(t) > -1;
    },g = 'gecko',w = 'webkit',s = 'safari',o = 'opera',h = document.documentElement,b = [(!(/opera|webtv/i.test(ua)) && /msie\s(\d)/.test(ua)) ? ('ie ie' + RegExp.$1) : is('firefox/2') ? g + ' ff2' : is('firefox/3.5') ? g + ' ff3 ff3_5' : is('firefox/3') ? g + ' ff3' : is('gecko/') ? g : is('opera') ? o + (/version\/(\d+)/.test(ua) ? ' ' + o + RegExp.$1 : (/opera(\s|\/)(\d+)/.test(ua) ? ' ' + o + RegExp.$2 : '')) : is('konqueror') ? 'konqueror' : is('chrome') ? w + ' chrome' : is('iron') ? w + ' iron' : is('applewebkit/') ? w + ' ' + s + (/version\/(\d+)/.test(ua) ? ' ' + s + RegExp.$1 : '') : is('mozilla/') ? g : '',is('j2me') ? 'mobile' : is('iphone') ? 'iphone' : is('ipod') ? 'ipod' : is('mac') ? 'mac' : is('darwin') ? 'mac' : is('webtv') ? 'webtv' : is('win') ? 'win' : is('freebsd') ? 'freebsd' : (is('x11') || is('linux')) ? 'linux' : '','js'];
    c = b.join(' ');
    if (navigator.userAgent.match(/iPad/i) != null) {
        c += (' ipad');
    }
    h.className += c;
    return c;
}

css_browser_selector(navigator.userAgent);
