
/**
 * Stylopis webu Dobra-Mama.cz
 *
 * @copyright  Copyright (c) 2011 Studio Fresh Net, s.r.o.
 * @author     Roman Pistek
 * @package    DobraMama
 */


var isMobile = navigator.userAgent.match(/Android/i) ||
               navigator.userAgent.match(/webOS/i) ||
               navigator.userAgent.match(/iPhone/i) ||
               navigator.userAgent.match(/iPod/i) || false,
    isOldIE = $.browser.msie && parseInt($.browser.version.slice(0, 1)) < 8;


var dmUI = function() {

    // public
    this.callbacks = {
        onPageReady: function() {}
    };
    
    // privates
    var _ui = this,
        
        realignLayout = function() {
            var scrLimits = {
                    min: {x: 960, y: 760},
                    max: {x: 1920, y: 1080}
                },
                winHeight = $(window).height();

            $('#wrapper').height((winHeight < scrLimits.min.y) ? scrLimits.min.y : ((winHeight > scrLimits.max.y) ? scrLimits.max.y : winHeight));
            var winWidth = $(window).width();
            $('#wrapper').width((winWidth < scrLimits.min.x) ? scrLimits.min.x : ((winWidth > scrLimits.max.x) ? scrLimits.max.x : winWidth))

            $('header, footer').appendTo($('body'));
        },

        bindEvents = function() {

            // break script in <IE8 and handhelds...
            if (isOldIE || isMobile) {
                return;
            }

            // browser window resized...
            $(window).resize(function() {
                realignLayout();
            });
            
            $('#fridge-content a')
                .bind('mouseenter', function() {
                    var cls = $(this).parent().attr('class');
                    $('#fridge-hover').hide().attr('class', '').addClass(cls).fadeIn(200);
                })
                .bind('mouseleave', function() {
                    $('#fridge-hover').hide().attr('class', '');
                });

            // Product sliding...
            $.nette.callbacks.beforePost = function(el) {
                $('#products .spinner').fadeIn(100);
            };
            $.nette.callbacks.beforeSnippetUpdate = function(id, html) {
                if (id.match(/productDetail$/)) {
                    var src = $('img', html).attr('src');
                    if ($.browser.msie) {
                        // work-around for IE...
                        src += '?random=' + new Date().getTime();
                    }
                    $('<img/>').attr('src', src).load(function() {
                        $('#products .wrapper').fadeOut($.browser.msie ? 0 : 300, function() {$(this).remove();});
                        $('#products .spinner').fadeOut(400);
                        $('<div class="snippet-wrapper">' + html + '</div>').hide().appendTo($('#' + id)).fadeIn($.browser.msie ? 0 : 200, function() {
                            var snippetWrapper = $('#products .snippet-wrapper');
                            snippetWrapper.replaceWith(snippetWrapper.html());
                        });
                    });
                } else {
                    $('#' + id).html(html);
                }
            };

            // Products list
            var plTimer;
            // - switch
            $('#prod-list .switch').bind('click', function() {
                var list = $('#prod-list .list');
                if (list.css('display') == 'none') {
                    $(this).fadeOut(200);
                    list.fadeIn(200);
                }
            });
            $('#prod-list .list')
                .bind('mouseleave', function() {
                    plTimer = setTimeout(function() {
                        $('#prod-list .list').fadeOut(200);
                        $('#prod-list .switch').fadeIn(200);
                    }, 400);
                })
                .bind('mouseenter', function() {
                    clearTimeout(plTimer);
                });
            $('#prod-list .list a').bind('click', function() {
                $('#prod-list .list').fadeOut(200);
                $('#prod-list .switch').fadeIn(200);
            });

            // - accordion
            $('#prod-list dt').live('click', function() {
                if ($(this).hasClass('active')) {return;}
                var acc = $(this).parents('dl');
                $('dt.active', acc).removeClass('active');
                $('div.active', acc).slideUp(200, function() {$(this).removeClass('active');});
                $(this).addClass('active');
                $(this).next('div').slideDown(200).addClass('active');
            });
        },
        
        initialize = function() {

            $('a.fancy').fancybox({
                centerOnScroll: true,
                overlayColor: '#2c6ba0',
                overlayOpacity: 0.75
            });

            // break initialization in <IE8 and handhelds...
            if (isOldIE || isMobile) {
                return;
            }

            $.preloadImages(function() {
                $('#wrapper').css({visibility: 'visible'});
                $('#page-overlay').fadeOut(777, function() {
                    _ui.callbacks.onPageReady();
                });
            });
            
            realignLayout();

            $('#wrapper').jparallax(
                {
                    takeoverFactor: 0.4,  // 0.68
                    takeoverThresh: 0.012  // 0.002
                },
                {   // background
                    yparallax: false, xtravel: 0.1, xorigin: 0
                },
                {   // fridge
                    yparallax: false, xtravel: 0.14, xorigin: 0
                },
                {   // table
                    yparallax: false, xtravel: 0.25, xorigin: 0
                },
                {   // nutri. values
                    yparallax: false, xtravel: 1, ytravel: 0.3, xorigin: 0.1, yorigin: 1
                },
                {   // prod. detail nav
                    yparallax: false, xtravel: 0.25, xorigin: 0
                },
                {   // fridge content
                    yparallax: false, xtravel: 0.14, xorigin: 0
                }
            );

            $('#fridge-content a[title], #prod-list .switch[title]').qtip({
                show: {
                    delay: 100
                },
                position: {
                    corner: {target: 'rightMiddle', tooltip: 'leftMiddle'}
                },
                style: {
                    tip: true,
                    width: {
                        min: 0,
                        max: 380
                    },
                    padding: '3px 6px',
                    border: {
                        radius: 8,
                        width: 0,
                        color: '#0d8ac9'
                    },
                    color: '#eee',
                    background: '#0d8ac9',
                    fontSize: '12px',
                    fontWeight: 'bold'
                }
            });
        };
        
    // public
    return {
        callbacks: _ui.callbacks,
        init: function() {
            initialize();
            bindEvents();
        }
    }
}();



// Images preloader
(function($) {
    // Arguments are image paths relative to the current page.
    $.preloadImages = function(callback) {
        var cache = [],

            // Function origin: http://ajaxian.com/archives/preloading-images-with-jquery
            parseStyleSheets = function() {
                var allImgs = [];//new array for all the image urls
                var k = 0; //iterator for adding images
                var progresses = [];
                var sheets = document.styleSheets; // array of stylesheets
                var isDone = function() {
                    for (var i = 0; i < progresses.length; i++) {
                        if (!progresses[i]) {return false;}
                    }
                    return true;
                };

                for(var i = 0; i<sheets.length; i++){//loop through each stylesheet

                    // kontroluje se POUZE hlavni stylopis
                    if (!sheets[i].href.match(/css\/screen\.css$/)) {continue;}

                    var cssPile = '';//create large string of all css rules in sheet
                    var csshref = (sheets[i].href) ? sheets[i].href : 'window.location.href';
                    var baseURLarr = csshref.split('/');//split href at / to make array
                    baseURLarr.pop();//remove file path from baseURL array
                    var baseURL = baseURLarr.join('/');//create base url for the images in this sheet (css file's dir)
                    if(baseURL!="") baseURL+='/'; //tack on a / if needed
                    if(document.styleSheets[i].cssRules){//w3
                        var thisSheetRules = document.styleSheets[i].cssRules; //w3
                        for(var j = 0; j<thisSheetRules.length; j++){
                            cssPile+= thisSheetRules[j].cssText;
                        }
                    }
                    else {
                        cssPile+= document.styleSheets[i].cssText;
                    }

                    //parse cssPile for image urls and load them into the DOM
                    var imgUrls = cssPile.match(/[^(]+.(gif|jpg|jpeg|png)/g);//reg ex to get a string of between a "(" and a ".filename"
                    if(imgUrls != null && imgUrls.length>0 && imgUrls != ''){//loop array

                        var arr = jQuery.makeArray(imgUrls);//create array from regex obj

                        // add <img> images
                        /*$('img').each(function() {
                            arr.push($(this).attr('src'));
                        });*/

                        // cache <img> & background images
                        jQuery(arr).each(function(){
                            /*allImgs[k] = new Image(); //new img obj
                            allImgs[k].src = (this[0] == '/' || this.match('http://')) ? this : baseURL + this;     //set src either absolute or rel to css dir*/
                            progresses[k] = false;
                            //allImgs[k] = $('<img/>').attr('src', (this[0] == '/' || this.match('http://')) ? this : baseURL + this)/*.get(0);
                            var path = this.replace('"', '');
                            var src = (path[0] == '/' || path.match('http://')) ? path : baseURL + path;
                            /*if (!src.match(/(background-kitchen\.jpg|table\.png)$/)) {
                                progresses[k] = true;
                                return;
                            }*/
                            if ($.browser.msie) {
                                // work-around for IE...
                                src += '?random=' + new Date().getTime();
                            }
                            $('<img/>').attr('src', src).attr('class', k)
                            .load(function() {
                                var key = $(this).attr('class');
                                progresses[key] = true;
                                if (isDone()) {
                                    return callback();
                                }
                            });
                            k++;
                        });
                    }
                } //loop
                
                return allImgs;
            };

        parseStyleSheets();
    }
})(jQuery);



// Repeater Plugin
(function ($) {
$.fn.repeat = function(times, string, callback) {
    // For each item matched
    this.each(function(){
        var buff = '';
        for(var i = 1; i <= times; i++){
            var rel = callback(i);
            string = rel ? $('<div>').append($(string).clone().attr('rel', rel)).remove().html() : string;
            buff += string;
        }
        $(this).append(buff);
    });
    return this;
};
})(jQuery);



// Vertically align function
(function ($) {
$.fn.vAlign = function(property, parent, symetry) {
    var prop = (property == 'padding') ? (symetry ? 'padding' : 'padding-top') : 'margin-top';
    var topPadding;
    /*return */this.each(function(i) {
        var ah = $(this).height();
        var ph = (parent ? parent : $(this).parent()).height();
        var mh = Math.ceil((ph - ah) / 2);
        if (i == 0) {topPadding = mh;}
        $(this).css(prop, mh + 'px' + (symetry ? ' 0' : ''));
    });
    return topPadding;
};
})(jQuery);



// Extended validation rules...
Nette.validators.FormValidators_contact = function(elem, args, val) {
    if ((/^\s*[+0-9\s]+\s*$/).test(val)) {
        // validating as phone number
        val = val.replace('+', '00').replace(/\s*/g, '');
        return (/^[0-9]{9,14}$/).test(val);
    } else {
        return Nette.validators.email(elem, args, val);
    }
};

