/**
 * Slideshow
 * 
 * Version: 0.1.1
 *
 * Changes:
 * 0.1.1
 * - Slideshow aangepast zodat hij met bestel functionaliteiten van de site werkt.
 * 0.1.0
 * - Slideshow omgezet naar namespace en acties voor knoppen toegevoegd
 */

function isdefined( variable)
{
        
    return (typeof(window[variable]) == "undefined")?  false: true;
}


(function($) {
        
        $.fn.slideshow = function(options, data){
                
                $.fn.slideshow.options.thumbContainer = this[0].id;
                var settings = $.fn.slideshow.options = $.extend($.fn.slideshow.options, options);
                
                var element = this[0];
                
                if(!settings.container) {
                        
                        alert('Geef container op!');
                        return;
                }
                
                // Kijk welkje kant hij op moet scrollen
                var height = $(element).height();
                var width = $(element).width();
                jQuery.fn.slideshow.x = height > width ? false : true;
                        
                // Maak thumbs aan
                $(data).each(function(k,v){
                        
                        $(element).append('<div style="background-image: url(\'' + v.low_src + '\');" class="slideshow-thumb"'
                                + ' id="'+ v.src +'" item_id="' + v.id + '" supply="' + v.supply + '"></div>');
                });
                // Koppel events aan thumbs
                $('#'+element.id+' div').click(function(e){
                        
                        pause();
                        show(element, e.currentTarget);
                });
                
                var len = ((96 + 6) * (data.length + 1)) + 2;
                
                $('#thumb-holder > div').wrapAll('<div style="width: ' + len + 'px"></div>');
                
                $.fn.slideshow.curr = ($('#'+element.id+' div:first').addClass('slideshow-thumb-clicked'))[0];
                
                // Maak eerste image aan
                $('#'+settings.container).append('<img id="slideshow-image" src="" />');
                
                // Koppel overige acties                
                if(typeof settings.play == 'string') {
                        
                        $('#' + settings.play).click(function(){
                                
                                play(element);
                        });
                }
                if(typeof settings.pause == 'string') {
                        
                        $('#' + settings.pause).click(pause);
                }
                if(typeof settings.previous == 'string') {
                        
                        $('#' + settings.previous).click(function(){
                                previous(element);
                        });
                }
                if(typeof settings.next == 'string') {
                        
                        $('#' + settings.next).click(function(){
                                next(element);
                        });
                }
                
                // Load and show first image
                show($('#'+element.id+' > div > div:first')[0], $('#'+element.id+' > div > div:first')[0]);
                // Start
                setTimeout(function() { play(element); }, 1000);
                
                $('#slideshow-image').click(function(){
                        
                        var img_part = $(this).attr('src').split('/');
                        var img = img_part[img_part.length - 1];
                        
                        //window.open(BASEURL + 'popup/' + PAGEID + '/' + img, 'Galerij', 'width='+screen.width+',height='+screen.height+',scrollbars=no,toolbar=no,location=no');
                        var url = window.location.href.split('/');
                        url = 'http://' + url[2] + BASEURL + 'popup/' + url[url.length-2] + '/' + url[url.length-1] + '/' + img;
                        
                        window.open(url, 'Galerij', 'width='+screen.width+',height='+screen.height+',scrollbars=no,toolbar=no,location=no');                
                });
        };
        
        $.fn.slideshow.options = {
                
                speed: 5000,                        // miliseconds
                effects: true,
                container: null,
                play: null,
                pause: null,
                previous: null,
                next: null
        };
        $.fn.slideshow.curr;
        $.fn.slideshow.timer;
        
        function show(element, e){
                
                $.fn.slideshow.curr = e;
                
                var s = 0;
                var x = jQuery.fn.slideshow.x;
                var ps = e;
                
                while(ps && ps.tagName.toLowerCase() == 'div') {
                        
                        if(ps == e){
                                ps = ps.previousSibling;
                                continue;
                        }
                        
                        if(x)
                                s += $(ps).width();
                        else
                                s += $(ps).height();
                                
                        ps = ps.previousSibling;
                }
                
                if(x)
                        $(element).scrollLeft(s);
                else
                        $(element).scrollTop(s);
                // Class names
                $('#' + $.fn.slideshow.options.thumbContainer + ' div').removeClass('slideshow-thumb-clicked').addClass('slideshow-thumb');
                
                $(e).removeClass('slideshow-thumb').addClass('slideshow-thumb-clicked');
                
                var src = e.id;
                
                $('#slideshow-image').fadeOut('fast',function(){
                        
                        $('#slideshow-image').attr('src', src).hide();
                        
                        //$('#bestellen').hide();
                });
                
                $.post(BASEURL + 'ajax/index/fetchSupplyInfo', {
                        
                        id: e.getAttribute('item_id')
                }, function(t) {
                        
                        var json = eval(t);
                        
                        preloadImage(src, function(){
                                
                                
                                $('#slideshow-image').attr('src', src);
                                
                                $('#slideshow-image').css('width', '');
                                $('#slideshow-image').css('height', '');
                                
                                if($('#slideshow-image').width() > $('#slideshow-image').height()) {
                                        setTimeout(function () {
                                                
                                                if($('#bestellen').css('display') == 'none') {
                                                
                                                        $('#slideshow-image').css('width', '790px');
                                                        
                                                } else {
                                                        
                                                        $('#slideshow-image').css('width', '480px');
                                                        $('#slideshow-image').css('height', '');
                                                }
                                        }, 100);
                                        if($('#bestellen').css('display') == 'none') {
                                                
                                                $('#slideshow-image').css('height', '');
                                                $('#slideshow-image').css('width', '790px');
                                        } else {
                                                
                                                $('#slideshow-image').css('width', '480px');
                                                $('#slideshow-image').css('height', '');
                                        }
                                } else {
                                        
                                        $('#slideshow-image').css('width', '480px');
                                        $('#slideshow-image').css('height', '');
                                }
                                
                                if(e.getAttribute('supply') == 'yes') {
                                        
                                        $('#bestellen').show();
                                        
                                if(typeof json == 'object') {
                                                
                                                // 
                                                $('div.bestellen-effect-row').empty();
                                                var i = 0;
                                                var options = '';
                                                
                                                $(json[1]).each(function(k,v){
                                                        
                                                        if(i == 2) {
                                                                $('div.bestellen-effect-row').append('<a class="bestellen-effect-knop" style="border-right-width: 0px" href="javascript:showEffect(\''+v.effect_id+'\')">'+v.name+'</a>');
                                                                i = 0;
                                                        } else
                                                                $('div.bestellen-effect-row').append('<a class="bestellen-effect-knop" href="javascript:showEffect(\''+v.effect_id+'\')">'+v.name+'</a>');
                                                        
                                                        options += '<option value="'+v.effect_id+'">'+v.name+'</option>';
                                                        
                                                        i++;
                                                });
                                                
                                                //
                                                $('table.bestellen-table tbody').empty();
                                                
                                                // foto's tonen
                                                if(typeof json[0]['photo'] == 'object')
                                                {
                                                
                                                $('table.bestellen-table tbody').append('<tr><th colspan="4">Foto:</th></tr>');
                                                
                                                $(json[0]['photo']).each(function(k,v){
                                                        
                                                        v.price = v.price.replace('.', ',');
                                                        v.size = v.size.replace('.', ',');
                                                        
                                                        if(v.price.indexOf(',') != -1) {
                                                                
                                                                var price = v.price.substr(v.price.indexOf(',') + 1);
                                                                
                                                                if(price.length == 1)
                                                                        price = v.price + '0';
                                                                else
                                                                        price = v.price;
                                                        } else
                                                                var price = v.price + ',00';;
                                                        
                                                        $('table.bestellen-table tbody').append('<tr><td><input type="hidden" value="'+v.format_id+'" name="format_id" /><input type="text" name="prijs" class="bestellen-prijs" /></td><td>'+v.size+'</td><td><select name="effect">'+options+'</select></td><td>&euro; '+price+'</td></tr>');
                                                });
                                                }
                                                
                                                // canvas tonen
                                                if(typeof json[0]['canvas'] == 'object')
                                                {
                                                
                                                $('table.bestellen-table tbody').append('<tr><th colspan="4">Foto op canvas:</th></tr>');
                                                
                                                $(json[0]['canvas']).each(function(k,v){
                                                        
                                                        v.price = v.price.replace('.', ',');
                                                        v.size = v.size.replace('.', ',');
                                                        
                                                        if(v.price.indexOf(',') != -1) {
                                                                
                                                                var price = v.price.substr(v.price.indexOf(',') + 1);
                                                                
                                                                if(price.length == 1)
                                                                        price = v.price + '0';
                                                                else
                                                                        price = v.price;
                                                        } else
                                                                var price = v.price + ',00';;
                                                        
                                                        $('table.bestellen-table tbody').append('<tr><td ><input type="hidden" value="'+v.format_id+'" name="format_id" /><input type="text" name="prijs" class="bestellen-prijs" /></td><td>'+v.size+'</td><td><select name="effect">'+options+'</select></td><td>&euro; '+price+'</td></tr>');
                                                });
                                                }
                                                
                                                // aluminium tonen
                                                if(typeof json[0]['aluminium'] == 'object')
                                                {
                                                
                                                $('table.bestellen-table tbody').append('<tr><th colspan="4">Foto op aluminium:</th></tr>');
                                                
                                                $(json[0]['aluminium']).each(function(k,v){
                                                        
                                                        v.price = v.price.replace('.', ',');
                                                        v.size = v.size.replace('.', ',');
                                                        
                                                        if(v.price.indexOf(',') != -1) {
                                                                
                                                                var price = v.price.substr(v.price.indexOf(',') + 1);
                                                                
                                                                if(price.length == 1)
                                                                        price = v.price + '0';
                                                                else
                                                                        price = v.price;
                                                        } else
                                                                var price = v.price + ',00';;
                                                        
                                                        $('table.bestellen-table tbody').append('<tr><td><input type="hidden" value="'+v.format_id+'" name="format_id" /><input type="text" name="prijs" class="bestellen-prijs" /></td><td>'+v.size+'</td><td><select name="effect">'+options+'</select></td><td>&euro; '+price+'</td></tr>');
                                                });
                                                }
                                                
                                                if(typeof json[0]['product'] == 'object')
                                                {
                                                
                                                $('table.bestellen-table tbody').append('<tr><th colspan="4">Overig:</th></tr>');
                                                
                                                $(json[0]['product']).each(function(k,v){
                                                        
                                                        v.price = v.price.replace('.', ',');
                                                        v.size = v.size.replace('.', ',');
                                                        
                                                        if(v.price.indexOf(',') != -1) {
                                                                
                                                                var price = v.price.substr(v.price.indexOf(',') + 1);
                                                                
                                                                if(price.length == 1)
                                                                        price = v.price + '0';
                                                                else
                                                                        price = v.price;
                                                        } else
                                                                var price = v.price + ',00';;
                                                        
                                                        $('table.bestellen-table tbody').append('<tr><td><input type="hidden" value="'+v.format_id+'" name="format_id" /><input type="text" name="prijs" class="bestellen-prijs" /></td><td>'+v.size+'</td><td><select name="effect">'+options+'</select></td><td>&euro; '+price+'</td></tr>');
                                                });
                                                }
                                                
                                                $('#bestellen-product-id').val(json[2]);
                                        }
                                } else {
                                        
                                        $('#bestellen').hide();
                                }
                                
                                var ph = $('#content-spacer').width() - ( $('#bestellen').css('display') == 'block' ? $('#bestellen').width() : 0 );
                                var ih = $('#slideshow-image').width();
                                
                                // Center vertical, image
                                $('#slideshow-image').css('marginLeft', ((ph-ih)/2)+'px');
                                
                                $('#slideshow-image').css('marginTop', '18px');
                                
                                setTimeout(function () {
                                        var ph = $('#content-spacer').width() - ( $('#bestellen').css('display') == 'block' ? $('#bestellen').width() : 0 );
                                        var ih = $('#slideshow-image').width();
                                        $('#slideshow-image').css('marginLeft', ((ph-ih)/2)+'px');
                                        $('#slideshow-image').css('marginTop', '18px');
                                }, 100);
                                
                                //alert($('#slideshow-image').width() + ', ' + $('#slideshow-image').height());
                                
                                setTimeout(function(){ $('#slideshow-image').fadeIn('fast', function(){ $('#slideshow-image').show(); }); }, 10);
                        });
                
                });
        };
        
        function play(element){
                
                $.fn.slideshow.timer = setTimeout(function(){
                        
                        next(element);
                        play(element);
                }, $.fn.slideshow.options.speed);
        };
        
        function pause(){
                
                clearTimeout($.fn.slideshow.timer);
        };
        
        function previous(element){
                
                pause();
                
                if(!$.fn.slideshow.curr.previousSibling){
                        
                        var ns = $.fn.slideshow.curr;
                        while(ns.nextSibling && ns.tagName.toLowerCase() == 'div'){
                                
                                ns = ns.nextSibling;
                        }
                        $.fn.slideshow.curr = ns;
                } else {
                        
                        $.fn.slideshow.curr = $.fn.slideshow.curr.previousSibling;
                }
                
                show(element, $.fn.slideshow.curr);
        };
        
        function next(element){
                
                pause();
                
                if(!$.fn.slideshow.curr.nextSibling){
                        
                        var ps = $.fn.slideshow.curr;
                        while(ps.previousSibling && ps.tagName.toLowerCase() == 'div'){
                                
                                ps = ps.previousSibling;
                        }
                        $.fn.slideshow.curr = ps;
                } else {
                        
                        $.fn.slideshow.curr = $.fn.slideshow.curr.nextSibling;
                }
                
                show(element, $.fn.slideshow.curr);
        };
})(jQuery);

// Hier een keer wat netjes van maken
var preloadImage = function(src, callback) {
        
        var Img = new Image();
        
        Img.onload = callback;
        
        Img.src = src;
        
        //checkLoad(Img, callback);
};

/*var checkLoad = function(Img, callback){
        
        //alert(Img.complete);
        
        if(Img.complete == true) {
                
                callback();
                return;
        }
        
        setTimeout(function(){ checkLoad(Img, callback) }, 10);
};*/

var AAP;


/**
 * Winkelwagen functies
 */
var sendSupply = function() {
        
        var url = window.location.toString().split('/');
        
        var Values = {
                product_id: $('#bestellen-product-id').val(),
                page_id: url[ url.length - 2 ]
        };
                
        var id = 0;
        
        $('table.bestellen-table tbody').find('td').each(function(k,v){
                
                $(v).find(':input').each(function(e,a){
                        
                        if(a.name == 'format_id') {
                                
                                id = $(a).val();
                                Values[id] = '';
                        } else
                        {

                                Values[id] += $(a).val() + '|';
                        }
                });
        });
        
        $.post(BASEURL + 'winkelwagen/addProducts', Values, function (t) {
                
                if($('#bestellen-melding').length == 0)
                        $('#bestellen').append('<div id="bestellen-melding" style="clear: both; text-align: center">Uw product(en) zijn toegevoegd</div>');
                
                $('#bestellen-total-price').html(t);
                
                $('#bestellen-melding').animate({
                        
                        opacity: 0
                }, 2500, 'swing', function(){ $(this).remove(); });
                
                // Waardes resetten
                $('table.bestellen-table tbody').find('td').each(function(k,v){
                
                        $(v).find(':input').each(function(e,a){
                                
                                if(a.name != 'format_id') {
                                        
                                        if($(a).attr('name') === 'effect') {
                                                
                                                var def = $(a).find('option:first').val();
                                                $(a).val(def);
                                        }                                 }
                        });
                });
        });
};

//

var showEffect = function (effect_id) {
        
        var el;
        
        $('#thumb-holder').find('div').each(function(k,v){
                
                if($(v).hasClass('slideshow-thumb-clicked')) {
                        
                        el = v;
                        return;
                }
        });
        
        $.post(BASEURL + 'ajax/index/effect', { id: effect_id, item_id: el.getAttribute('item_id') }, function(t){
                
                $('#slideshow-image').attr('src', t[0]);
        }, 'json');
};

//

var showEffectPopup = function (effect_id, item_id) {
        
        $.post(BASEURL + 'ajax/index/effect', { id: effect_id, item_id: item_id }, function(t){
                
                $('#slideshow-image').attr('src', t[0]);
        }, 'json');
};

var updateRowCount = function (element, product_id, format_id, effect_id) {
        
        var value = $(element).val();
        
        if(value == '') return;
        
        window.location = BASEURL + 'winkelwagen/update/' + product_id + '/' + format_id + '/' + effect_id + '/' + value;
};

var removeRow = function (product_id, format_id, effect_id) {
        
        window.location = BASEURL + 'winkelwagen/remove/' + product_id + '/' + format_id + '/' + effect_id;
};

var formAdresgegevensCheck = function (form) {
        
        var mailRegex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        var noError = true;
        
        $(form).find(':text').each(function(k,v){
                
                if($(v).attr('name') === 'email' && $(v).val() != '') {
                        // Check email adres
                        
                        if($(v).val().match(mailRegex) === null) {
                                
                                removeMessage(v);
                                addMessage(v, "Opgegeven mail adres klopt niet");
                                noError = false;
                        } else {
                                
                                removeMessage(v);
                        }
                } else {
                        // Check alsof veld niet leeg is
                        
                        if($(v).val() == '') {
                                
                                addMessage(v, "Veld mag niet leeg zijn");
                                noError = false;
                        } else {
                                
                                removeMessage(v);
                        }
                }
        });
        
        return noError;
};

var addMessage = function(element, msg) {
        
        // Haal element positie op.
        element = $(element)
        var width = element.width();
        var position = element.position();
        
        element.after("<div class=\"ww-form-message\" style=\"top: " + position.top + "px; left: " + (position.left + width + 4) + "px; \">" + msg + "</div>");
};

var removeMessage = function (element) {
        
        // Verwijder message element
        $(element.parentNode).find('div.ww-form-message').remove();
};

var saveOrder = function () {
        
        $.post(BASEURL + 'winkelwagen/saveOrder', {}, function(t){
                
                if(t.indexOf('ERROR') == -1) {
                        // Succes
                        $('#form1').submit();
                } else {
                        
                        alert(t.replace('ERROR:'));
                }
        });
};
