/**
 * description: jQuery custom scripts
 * for: Odbitker.pl
 * 
 * @author: Dariusz Pobożniak (http://pobozniak.pl)
 * @copyrights: Dariusz Pobożniak 2010
 *
 */

$(function() {
    $('#femail').inputFocus();
    $('#contactlink').nyroModal({ height: 150 });
    basket();
    switchTableView();
    boxSteps();
    scrollGallery();
    $('#big').bind('contextmenu', function() {
        return false;
    })
    $('#basketform').validate();
    alerts();
   
    shortcut.add("Right",function() {
        if ($('.imgpagin .next').hasClass('active')) {
            var next = $('.active', '#scrollable').next();
            Gallery.goNavi(next);
        }
    });
    
    shortcut.add("Left",function() {
    if ($('.imgpagin .prev').hasClass('active')) {
            var prev = $('.active', '#scrollable').prev();
            Gallery.goNavi(prev);
        }
    });

})




/* BASKET 
 ---------------------------------------------------------------------------- */

/**
 * Basket class
 */
var Basket = {
    totalPrice: 0.00,
    buyItems: 0,
    
    readBasket: function() {
        $('#printtypes input').each(function() {
            var $inputName = parseInt($(this).attr('name').split('-')[1]),
                $this = $(this);
            $this.val(0);
            $.ajax({
                url: 'cart/read.php',
                dataType: 'json',
                success: function(data) {
                    for (var n in data) {
                        for (var m in data[n]) {
                            var tmp = data[n][m].split(':');
                            if (n == Gallery.picSrc && parseInt(m) == $inputName) {
                                $this.val(tmp[0]);
                            } 
                        }
                        
                    }
                }
            });
        });
    },
    
    setTotalPrice: function() {
        this.totalPrice = 0.00;
        this.buyItems = 0;
        this.read();
    },
    
    read: function() {
        $.ajax({
            url: 'cart/read.php',
            dataType: 'json',
            success: function(data) {
                // if there's something in cart
                if (data) {
                    for (var n in data) {
                        for (var m in data[n]) {
                            var tmp = data[n][m].split(':');
                            Basket.totalPrice += (parseFloat(tmp[0]) * parseFloat(tmp[1]));
                            Basket.buyItems += parseInt(tmp[0]);
                        }
                    }
                } else {
                    Basket.totalPrice = 0.00;
                    Basket.buyItems = 0;
                }
                if (Basket.totalPrice == 0.00 && $('#basketform').length > 0) {
                    var href = $('#galback').attr('href');
                    document.location = href; 
                }
                Basket.getTotalPrice();
            }
        });
    },
    
    getTotalPrice: function() {
        var emptybsk = $('<span id="emptybsk" class="btn" style="background: #b4b4b4; cursor:default;">Koszyk jest pusty</span>');
        $('#emptybsk').remove();
        if (Basket.totalPrice == 0.00) {
            $('#basketlink').hide().after(emptybsk);
        } else {
            $('#basketlink').show();
        }
        var txt = parseFloat(Basket.totalPrice).toFixed(2) + ' zł';
        $('#buy_total, #step1_buytotal, #step2_buytotal, #step2_buytotalsum').text(txt);
        $('#step2_buyitems').text('ilość odbitek: ' + Basket.buyItems);
    },
    
    addDelivery: function() {
        $('#deliverytypes input').click(function() {
            var deliveryPrice = $(this).parent().next().text().replace(' zł', '');
            var totalSum = parseFloat(Basket.totalPrice)+parseFloat(deliveryPrice);
            $('#deliverycost').text(deliveryPrice + ' zł');
            $('#step2_buytotalsum').text(totalSum.toFixed(2) + ' zł');
        })
    },
    
    deleteFromBasket: function() {
        $('#prodtable .delete').click(function() {
            Basket.deleteItem(this);
        })
    },
    
    deleteItem: function(obj) {
        var tr = $(obj).parent().parent();
        var picSrc = tr.find('img').attr('src').replace('/0-', '/2-');
        var inputName = tr.find('input').attr('name').split('-')[1];
        $.ajax({
            type: 'get',
            data: 'filename='+picSrc+'&filesize='+inputName,
            url: 'cart/delete.php',
            success: function() {
                Basket.setTotalPrice();
                tr.fadeOut(500, function(){ $(this).remove(); });
            }
        });
    },
    
    btnClick: function($obj, $input) {
        if ($obj.hasClass('minus')) {
            var $newval = parseInt($input.val())-1;
            if ($newval < 0) {
                $input.val(0);
            } else {
                $input.val($newval);
            }        
        }
        if ($obj.hasClass('plus')) { 
            $input.val(parseInt($input.val())+1);
        }
    },
    
    addToBasket: function() {
        var priceClass = '.p2';
        $('#prodtable .t6 span').click(function() {
            Gallery.picSrc = $(this).parent().parent().find('img').attr('src').replace('/0-', '/2-');
            priceClass = '.t5';
        });
        $('#printtypes .btn span, #prodtable .t6 span').click(function() {
            var $input = $(this).parent().parent().find('input'),
                $this = $(this);
            Basket.btnClick($this, $input);
            var $inputVal = $input.val(),
                $inputName = $input.attr('name').split('-')[1],
                $price = $this.parent().siblings(priceClass).text().replace('zł',''),
                $val = 0;
            // don't let to set count to -1
            //if ($inputVal > 0) {
                switch (this.className) {
                    case 'plus': $val = 1; break;
                    case 'minus': $val = -1; break;
                    default: $val = 1; break;
                }
                $.ajax({
                    type: 'get',
                    data: 'filename='+Gallery.picSrc+'&filesize='+$inputName+'&files='+$val+'&price='+$price,
                    url: 'cart/add.php',
                    success: function(msg) {
                        Basket.setTotalPrice();
                        $this.parent().siblings('.t7').text((parseInt($inputVal)*parseFloat($price)).toFixed(2) + ' zł');
                    }
                });
            //}
        })
    }
}

function basket() {
    Basket.read();
    Basket.getTotalPrice();
    Basket.addToBasket();
    if ($('#deliverytypes').length) {
        Basket.addDelivery();
    }
    if ($('#basketform').length > 0) {
        $('.t6 input', '#prodtable').each(function() {
            if ($(this).val() == 0) {
                Basket.deleteItem(this);
            }
        })
    }
    Basket.deleteFromBasket();
}


/* GALLERY 
 ---------------------------------------------------------------------------- */
 
/**
 * Gallery class
 */
var Gallery = {
    // Class properties
    container : '#scrollable',
    photo: '#bigimg',
    photoObj: Object,
    activeClass: 'active',
    visibleClass: 'visible',
    hideClass: 'hide',
    mainGalleryLength: 24,
    picSrc: '',
    pageNo: 1,
    pageCount: 1,
    picId: 1,
    prevId: 1,
    nextId: 1,
    
    init: function() {
        this.photoObj = $(this.photo); 
    },
    
    getNumberOfPhotos: function() {
        return parseInt($('li', this.container).length);
    },
    
    getNumberOfPages: function() {
        return Math.ceil(parseInt($('li', this.container).length)/this.mainGalleryLength);
    },
    
    showSiblings: function() {
        this.picId = parseInt($('.' + this.activeClass, this.container).attr('id').replace('pic-', ''));
        this.pageNo = Math.ceil(Gallery.picId/Gallery.mainGalleryLength);
        this.prevId = this.picId-3;
        this.nextId = this.picId+4;
       
        this.showNavActivity();
        
        $('.' + this.activeClass, this.container)
            .siblings().addClass('hide')
            .end()
            .nextUntil('#pic-'+this.nextId).removeClass().addClass(this.visibleClass)
            .end()
            .prevUntil('#pic-'+this.prevId).removeClass().addClass(this.visibleClass);
            
        this.setCounter(this.picId, this.getNumberOfPhotos());
    },
    
    setCounter: function(pic, gal) {
        $('.count','#pagetitle').html(pic + ' | ' + gal);
    },
    
    showNavActivity: function() {
        if (this.picId < 3) {
            this.nextId = 7;
            if (this.picId == 1) {
                $('.imgpagin .prev').removeClass('active').addClass('inactive');
            } else {
                $('.imgpagin .prev').removeClass('inactive').addClass('active');
            }
        } else {
            $('.imgpagin .prev').removeClass('inactive').addClass('active');
        }
        if (this.picId > (this.getNumberOfPhotos()-4)) {
            this.prevId = (this.getNumberOfPhotos()-6);
            if (this.picId == this.getNumberOfPhotos()) {
                $('.imgpagin .next').removeClass('active').addClass('inactive');
            } else {
                $('.imgpagin .next').removeClass('inactive').addClass('active');
            }
        } else {
            $('.imgpagin .next').removeClass('inactive').addClass('active');
        }
    },
    
    goNavi: function(obj) {
        this.photoObj.attr('src', 'gfx/ajaxload.gif');
        $('.' + this.activeClass, this.container)
            .removeClass().addClass('hide')
            .siblings().removeClass().addClass(this.hideClass);
            obj.removeClass().addClass(this.activeClass);
        Gallery.picSrc = $('img', '.' + this.activeClass).attr('src').replace('/1-', '/2-');
        picZoomSrc = $('img', '.' + this.activeClass).attr('src').replace('/1-', '/3-');
        //alert (picZoomSrc);
        $("a#zoomer").attr("href", picZoomSrc);

        this.showBig(Gallery.picSrc);
        this.showSiblings();
        Basket.readBasket();
    },
    
    contains: function(a, e) {
        for(j=0;j<a.length;j++)if(a[j]==e)return true;
        return false;
    },
    
    unique: function(a) {
        tmp = new Array(0);
        for(i=0;i<a.length;i++){
        	if(!this.contains(tmp, a[i])){
        		tmp.length+=1;
        		tmp[tmp.length-1]=a[i];
        	}
        }
        return tmp;
    },
    
    showBig: function(url) {
        var img = $('#bigimg');
        img.attr('src', url);
    },
    
    zoomowanie: function() {
   				//Examples of how to assign the ColorBox event to elements

        	 
   },
    
    
    initFilter: function() {
        var listOfTags = '';
        var arrayOfTags = [];
        $('li', this.container).each(function() {
            if ($(this).attr('rel')) {
                listOfTags += $(this).attr('rel') + ',';
            }
        });
        
        arrayOfTags = this.unique(listOfTags.split(','));
        arrayOfTags.pop();
        if (arrayOfTags.length) {
            var formEl = '<div id="filters">';
            $.each(arrayOfTags, function(index, value) {
                formEl += '<input type="checkbox" id="filter'+index+'" value="'+value+'" /> <label for="filter'+index+'">'+value+'</label> ';
            })
            formEl += '</div>';
            $(formEl).appendTo('#panelztagami .zawartosc');
        }
    },
    
    startFilter: function() {
        var arrayOfChecked = [];
        $('#filters input').click(function() {
            var $inputValue = $(this).val();
            if (this.checked === true) {
                arrayOfChecked.push($inputValue);
            } else {
                arrayOfChecked = jQuery.grep(arrayOfChecked, function(value) {
                    return value != $inputValue;
                })
            }
            $.ajax({
                url: 'ajax.php',
                type: 'post',
                data: 'tab='+arrayOfChecked,
                success: function(msg) {
                    $('ul', Gallery.container).html(msg);
                    Gallery.setCounter('1', Gallery.getNumberOfPhotos());
                    Gallery.picId = 1;
                    Gallery.pageNo = 1;
                    if ($('#photo').is(':visible')) {
                        $('li:first', Gallery.container).addClass(Gallery.activeClass).click();
                        Gallery.showSiblings();
                    } else {
                        $('li', Gallery.container)
                            .addClass(Gallery.hideClass)
                            .filter(':first').removeClass().addClass(Gallery.visibleClass)
                            .nextUntil('#pic-25').removeClass().addClass(Gallery.visibleClass);
                        Gallery.setPaginButtons();
                    }
                    Gallery.showNavActivity();
                }
            })
        })
    },
    
    goHome: function() {
        $('#photo').hide();
        var visibleImgages = $('li:visible', Gallery.container).length;
        $('#pagetitle .pagin').removeClass('imgpagin').addClass('sitepagin');
        //var p = Math.ceil(Gallery.picId/Gallery.mainGalleryLength);
        // bug: if photo is last on the current page it goes to the next page, it's the fix
        var plus = Gallery.picId % Gallery.mainGalleryLength == 0 ? Gallery.mainGalleryLength : 0;
        var startId = (Math.floor(Gallery.picId/Gallery.mainGalleryLength)*Gallery.mainGalleryLength)+1-plus;
        var stopId = startId + Gallery.mainGalleryLength;
        var to = stopId - 1;
        if (Gallery.getNumberOfPhotos() <= Gallery.mainGalleryLength) {
            to = Gallery.getNumberOfPhotos();
        }
        $('li', Gallery.container).removeClass().addClass(Gallery.hideClass).each(function() {
            var id = parseInt($(this).attr('id').replace('pic-', ''));
            if (id >= startId && id < stopId) {
                $('li#pic-'+id, Gallery.container).removeClass().addClass('visible');
            }
        });
        Gallery.setCounter(startId + '-' + to, Gallery.getNumberOfPhotos());
        this.setPaginButtons();
    },
    
    setPaginButtons: function() {
        if (this.pageNo == 1) {
            $('.sitepagin .prev').removeClass('active').addClass('inactive');
        } else {
            $('.sitepagin .prev').removeClass('inactive').addClass('active');
        }
        if (this.pageNo == this.getNumberOfPages()) {
            $('.sitepagin .next').removeClass('active').addClass('inactive');
        } else {
            $('.sitepagin .next').removeClass('inactive').addClass('active');
        }
        if (this.getNumberOfPhotos() <= this.mainGalleryLength) {
            $('.sitepagin .prev, .sitepagin .next').removeClass('active').addClass('inactive');
        }
    }
}

function scrollGallery() {
    $('li', Gallery.container).live('click', function() {
        Gallery.photoObj.attr('src', 'gfx/ajaxload.gif');
        $(this)
            .siblings().removeClass().addClass(Gallery.hideClass)
            .end()
            .removeClass().addClass(Gallery.activeClass);
        $('#pagetitle .pagin').removeClass('sitepagin').addClass('imgpagin');
        Gallery.picSrc = $('img',this).attr('src').replace('/1-', '/2-');
        picZoomSrc = $('img',this).attr('src').replace('/1-', '/3-');
        //alert (picZoomSrc);
        $("a#zoomer").attr("href", picZoomSrc);
        
        $('#photo').show();
        Gallery.showBig(Gallery.picSrc);
        Gallery.showSiblings();
        Basket.readBasket();
    })/* .filter('.' + Gallery.activeClass).click() */;
    
    $('.imgpagin .next').live('click', function() {
        if ($(this).hasClass('active')) {
            var next = $('.active', '#scrollable').next();
            Gallery.goNavi(next);
        }
    })
    
    $('.imgpagin .prev').live('click', function() {
        if ($(this).hasClass('active')) {
            var prev = $('.active', '#scrollable').prev();
            Gallery.goNavi(prev);
        }
    })
    
    $('.sitepagin .next').live('click', function() {
        if ($(this).hasClass('active')) {
            var start = parseInt($('li.visible:last', Gallery.container).attr('id').replace('pic-', ''));
            var stop = start + Gallery.mainGalleryLength; 
            $('li', Gallery.container).removeClass().addClass(Gallery.hideClass).each(function(index) {
                var i = ++index;
                if (i>start && i<=stop) {
                    $(this).removeClass().addClass(Gallery.visibleClass);
                }
            })
            var visibleImages = $('li.'+Gallery.visibleClass, Gallery.container).length;
            if (visibleImages < Gallery.mainGalleryLength) {
                stop = Gallery.getNumberOfPhotos();
            }
            Gallery.setCounter((start+1) + '-' + stop, Gallery.getNumberOfPhotos());
            Gallery.pageNo+=1;
            Gallery.setPaginButtons();
        }
    })
    
    $('.sitepagin .prev').live('click', function() {
        if ($(this).hasClass('active')) {
            var stop = parseInt($('li.'+Gallery.visibleClass+':first', Gallery.container).attr('id').replace('pic-', ''));
            var start = stop - Gallery.mainGalleryLength;
            $('li', Gallery.container).removeClass().addClass(Gallery.hideClass).each(function(index) {
                // index iterates from 0
                var i = ++index; // start from 1
                if (i>=start && i<stop) {
                    $(this).removeClass().addClass(Gallery.visibleClass);
                }
            })
            Gallery.setCounter(start + '-' + (stop-1), Gallery.getNumberOfPhotos());
            Gallery.pageNo-=1;
            Gallery.setPaginButtons();
        }
    })
    // Back to photo listing
    $('#galback').click(function() {
        Gallery.goHome();
    })


  
    Gallery.init();
    Gallery.goHome();
    Gallery.initFilter();
    Gallery.startFilter();
    Gallery.zoomowanie();
  
    
}


/* OTHER SCRIPTS 
 ---------------------------------------------------------------------------- */

function switchTableView() {
    var clicked = 0;
    var switcher = $('<p id="switchview" class="view1"><span></span></p>');
    $('#prodtable').before(switcher);
    switcher.click(function() {
        clicked++;
        $this = $(this);
		$this.toggleClass('view2');
        if (clicked == 1) {
            $this.find('span').stop().animate({
                top: 0,
                left: [32, 'linear']
            }, 500, function() {
                $('.prodlist img').fadeOut('300');
            })
        }
        if (clicked == 2) {
            $this.find('span').stop().animate({
                top: 0,
                left: [0, 'linear']
            }, 500, function() {
                $('.prodlist img').fadeIn('300');
            })
            clicked = 0;
        }
    })
}

function boxSteps() {
    $('#step2').css('display', 'none');
    function showSteps(toShow, toHide) {
        $('#' + toShow).css('display', 'none');
        $('#' + toHide).css('display', 'block');
        $('#bskstep p').removeClass(toShow).addClass(toHide);
    }
    $('#bskstep a').click(function(e) {
        e.preventDefault();
        var hash = this.hash;
        if (hash == '#step2') {
            showSteps('step1', 'step2');
        }
        else if (hash == '#step1') {
            $('input[name="delivery"]').attr('checked', false);
            $('#deliverycost').text('0.00 zł');
            Basket.getTotalPrice();
            showSteps('step2', 'step1');
        }
    })
    $('button', '#step1').click(function(e) {
        e.preventDefault();
        showSteps('step1', 'step2');
    })
}

function alerts() {
    $('#alertbox').animate({opacity: 1.0}, 8000).fadeOut(1000);
}
