﻿/**
 *
 * ql.lib JavaScript Library
 * http://www.qplage.com
 *
 * Copyright 2011, Adam Zakrzewski
 * Release under the GPL 3.0 License
 *
 */

//initialization
var ql = ql || {};

ql.lib = {
    date: {
        /*
         * get week number
         * @param {string[YYYY/MM/DD], object[Date]} value
         * @return number
         *
         * Monday is first day
         */
        getWeek: function(value){
            var myDate;
            (typeof(value) == 'string') ? myDate = new Date(value) : myDate = value;
            var firstJan = new Date(myDate.getFullYear(), 0, 1);
            return Math.ceil((((myDate - firstJan) / 86400000) + firstJan.getDay())/7);
        },
        /*
         * check if date is in this week
         * @param {string[YYYY/MM/DD], object[Date]} value [YYYY/MM/DD]
         * @return bool
         */
        sameWeek: function(value){
            var now = new Date(),
            myDate,
            today = new Date(now.getFullYear()+'/'+(now.getMonth()+1)+'/'+now.getDate());
            (typeof value === 'string') ? myDate = new Date(value) : myDate = value;

            //replace that Monday is 0, Sunday is 6 day
            var todayGetDay = today.getDay(),
            myDateGetDay = myDate.getDay();
            if(todayGetDay == 0){
                todayGetDay = 7;
            }
            todayGetDay--;

            if(myDateGetDay == 0){
                myDateGetDay = 7;
            }
            myDateGetDay--;

            return (today.getTime() - (todayGetDay*86400000)) == (myDate.getTime() - (myDateGetDay*86400000));
        }
    },
    time: {
        timer: function(timeStr, $selector, callback){
            var patt = /^([0-9]){1,2}\:([0-5][0-9])$/;	//example 3:12 - 3min 12sec
            if(patt.test(timeStr)){
                var timeArray = timeStr.split(':'),
                timeLeft = parseInt(timeArray[0])*60 + parseInt(timeArray[1]);

                var timerInterval = setInterval(function(){
                    if(timeLeft >= 0){
                        var min, sec;
                        min = Math.floor(timeLeft / 60);
                        sec = timeLeft - (min * 60);
                        (min < 10) ? min = '0'+min : null;
                        (sec < 10) ? sec = '0'+sec : null;
                        $selector.html(min+':'+sec);
                        timeLeft--;
                    }
                    else{
                        clearInterval(timerInterval);
                        window[callback]();
                    }
                }, 1000)
            }
        },
        timerFromTimeToTime: function(timeStr1, timeStr2, $selector, callback){
            var date1 = new Date(timeStr1),
            date2 = new Date(timeStr2),
            amount = Math.floor((date2.getTime() - date1.getTime()) / 1000);

            var timerInterval = setInterval(function(){
                if(amount >= 0){
                    var days = 0,
                    hours = 0,
                    mins = 0,
                    secs = 0.
                    temp = amount,
                    out = '';

                    days = Math.floor(temp/86400);
                    temp = temp%86400;

                    hours = Math.floor(temp/3600);
                    temp = temp%3600;

                    mins = Math.floor(temp/60);
                    temp = temp%60;

                    secs = Math.floor(temp);

                    if(days){
                        (days == 1) ? out += '1 dzień, ' : out += days + ' dni, ';
                    }

                    if(hours){
                        (hours < 10) ? out += '0' + hours + ':' : out += hours + ':';
                    }
                    else{
                        out += '00:';
                    }

                    if(mins){
                        (mins < 10) ? out += '0' + mins + ':' : out += mins + ':';
                    }
                    else{
                        out += '00:';
                    }

                    if(secs){
                        (secs < 10) ? out += '0' + secs : out += secs;
                    }
                    else{
                        out += '00';
                    }

                    $selector.html(out);
                    amount--;
                }
                else{
                    clearInterval(timerInterval);
                    window[callback]();
                }
            }, 1000)
        }
    },
    form: function(selector){
        //replace submit button
        var btnSubmit = function(){
            $(selector + ' input[type="submit"][data-replace="true"]').each(function(){
                var $self = $(this),
                val = $self.val(),
                cls = '';
                if($self.attr('class')){
                    cls = $self.attr('class')
                }
                var $a = $('<a href="#" class="'+cls+'">'+val+'</a>');

                $self.after($a).hide();
                $a.click(function(){
                    $self.trigger('click');
                    return false;
                })
            })
        }();
        
        // placeholder
        var placeholder = function(){
            var test = document.createElement('input');
            if(!('placeholder' in test)){
                $(selector + ' [placeholder]').each(function(){
                    var $this = $(this),
                    placeholderVal = $this.attr('placeholder');
                    $this.val(placeholderVal).addClass('placeholder');
                    $this.focus(function(){
                        $this.removeClass('placeholder');
                        if($this.val() == placeholderVal){
                            $this.val('');
                        }
                    });
                    $this.blur(function(){
                        if($this.val() == ''){
                            $this.val(placeholderVal);
                            $this.addClass('placeholder');
                        }
                    });
                });
            }
        }();
        
        //submit
        var submitForm = function(){
            //validate
            var validate = function(){
                var $this = $(this),
                    test,
                    returnVal = true,
                    $input,
                    radioChecked = [];

                //required 
                test = document.createElement('input');
                if(!('required' in test)){
                    $(selector + ' [required]').each(function(){
                        $input = $(this);
                        //text, email, textarea
                        if(($input.attr('type') == 'text') || ($input.attr('type') == 'email') || (this.type == 'textarea')){
                            if(($input.val() == '') || ($input.val() == $input.attr('placeholder'))){
                                returnVal = false;
                                $input.addClass('validateError').parent().addClass('validateError');
                            }
                            else{
                                $input.removeClass('validateError').parent().removeClass('validateError');
                            }
                        }
                        //checkbox
                        if($input.attr('type') == 'checkbox'){
                            if($input.attr('checked') != 'checked'){
                                returnVal = false;
                                $input.addClass('validateError').parent().addClass('validateError');
                            }
                            else{
                                $input.removeClass('validateError').parent().removeClass('validateError');
                            }
                        }

                    })
                }

                //email
                if(!('type="email"' in test)){
                    $(selector + ' input[type="email"]').each(function(){
                        $input = $(this);
                        if(!/^([a-zA-Z0-9_+\.\-]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/.test($input.val())){
                            returnVal = false;
                            $input.addClass('validateError').parent().addClass('validateError');
                        }
                        else{
                            $input.removeClass('validateError').parent().removeClass('validateError');
                        }
                    })
                }

                /*
                //add class to form
                if(!returnVal){
                    $(selector).addClass('validateError');
                }
                else{
                    $(selector).removeClass('validateError');
                }

                return returnVal;
                 */

                return returnVal;
            };
            
            // ajax submit
            var ajaxSubmit = function(){
                if($(selector).attr('data-submit') == 'ajax'){
                    var $this = $(selector),
                        dataType = 'text';
                        dataMethod = 'get';
                    if($this.attr('data-type')){
                        dataType = $this.attr('data-type');
                    }
                    if($this.attr('method')){
                        dataMethod = $this.attr('method');
                    }
                    if(!$this.attr('data-complete')){
                        alert('I can\'t find data-complete attribute.');
                    }

                    $.ajax({
                        type: dataMethod,
                        url: $this.attr('action'),
                        data: $this.serialize(),
                        dataType: dataType,
                        success: function(data){
                            window[$this.attr('data-complete')](data);
                        }
                    })
                    return false;
                }
                else{
                    return true;
                }
            };
            
            //submit
            $(selector).submit(function(){
                if(validate()){
                    return ajaxSubmit();
                }
                return false;
            });
        }();
        
        
        
           
        
        
        
        
        
        
    //		btnRadio: function(){
    //			$('input[type="radio"]').each(function(){
    //				var $this = $(this),
    //					attrName = $this.attr('name');
    //				$this.hide().parent().addClass('inputRadio');
    //				if($this.attr('checked') == 'checked'){
    //					$this.parent().addClass('inputRadioActive');
    //				}
    //				$this.parent().click(function(){
    //					//remove all checked
    //					$('input[type="radio"][name="'+attrName+'"]').removeAttr('checked').parent().removeClass('inputRadioActive');
    //					//set checked
    //					$this.attr('checked', 'checked');
    //					$this.parent().addClass('inputRadioActive');
    //				});
    //			});
    //		},
    //		btnCheckbox: function(){
    //			$('input[type="checkbox"]').each(function(){
    //				var $this = $(this);
    //				$this.hide().parent().addClass('inputCheckbox');
    //				if($this.attr('checked') == 'checked'){
    //					$this.parent().addClass('inputCheckboxActive');
    //				}
    //				$this.parent().click(function(){
    //					if($this.attr('checked') == 'checked'){
    //						$this.removeAttr('checked');
    //						$this.parent().removeClass('inputCheckboxActive');
    //					}
    //					else{
    //						$this.attr('checked', 'checked');
    //						$this.parent().addClass('inputCheckboxActive');
    //					}
    //				});
    //			});
    //		},
    //		placeholder: function(){
    //			$('input[data-placeholder]').each(function(){
    //				var $this = $(this),
    //					placeholderVal = $this.attr('data-placeholder');
    //				$this.val(placeholderVal).addClass('placeholder');
    //				$this.focus(function(){
    //					$this.removeClass('placeholder');
    //					if($this.val() == placeholderVal){
    //						$this.val('');
    //					}
    //				});
    //				$this.blur(function(){
    //					if($this.val() == ''){
    //						$this.val(placeholderVal);
    //						$this.addClass('placeholder');
    //					}
    //				});
    //			});
    //		},
    //		
        
                
                
    },
    popup:{
        config: {
            closeTxt: ''
        },
        create: function(content, cls){
            $('body #popup').remove();
            if(!cls){
                cls = '';
            }
            $('body').append('<div id="popup" class="'+cls+'">'+content+'<span class="popupClose">'+ql.lib.popup.config.closeTxt+'</span></div>');
            var $popup = $('#popup'),
            $window = $(window),
            pW = $popup.innerWidth(),
            pH = $popup.innerHeight(),
            wW = $window.width(),
            wH = $window.height(),
            sT = $window.scrollTop();
            //set center
            $popup.css({
                top: Math.round((wH-pH)/2),
                left: Math.round((wW-pW)/2)
            })
            //close handler
            $popup.find('.popupClose').click(function(){
                ql.lib.popup.remove();
            })
        },
        remove: function(){
            $('body #popup').remove();
        }
    },
    list: {
        filterList: function(){
            var dataFilter;
            $('ul[data-filterlist]').each(function(key, val){
                var filterRelation = $(this).attr('data-filterrelation');
                $(this).find('li').click(function(){
                    dataFilter = $(this).attr('data-filter');
                    if(dataFilter != 'all'){
                        $('ul[data-filteredlist][data-filterrelation='+filterRelation+'] li').each(function(key, val){
                            var $this = $(this);
                            if($this.attr('data-filterdata') != dataFilter){
                                $this.fadeOut();
                            }
                            else{
                                $this.fadeIn();
                            }
                        })
                    }
                    else{
                        $('ul[data-filteredlist][data-filterrelation='+filterRelation+'] li').fadeIn();
                    }
                })
            })
        }
    },
    window:{
        scrollAnimate: function(){
            $('a[href*="#"]').click(function(){
                var $target = $(this.hash);
                if($target.length){
                    var targetOffset = $target.offset().top;
                    $('html,body').stop().animate({
                        scrollTop: targetOffset
                    }, 1000);
                    return false;
                }
            })
        },
        copyToClipboard: function(text){
            window.prompt('Copy to clipboard: Ctrl+C, Enter', text);
        },
        parseUrl: function(){
            var href = window.location.href,
                params = href.split('?'),
                param = {},
                url = {
                    params: []
                },
                temp;
            //get params
            if(params[1]){
                params = params[1];
                params = params.split('&');
                for(var i=0, paramsLength = params.length; i<paramsLength; i++){
                    temp = params[i].split('=')
                    param = {
                        name: temp[0],
                        val: temp[1]
                    }
                    url.params.push(param);
                }
            }
            return url;
        },
        checkUrlHash: function(callback){
            var hash,
                hashArr = [];
            setInterval(function(){
                if(window.location.hash != hash){
                    hash = window.location.hash;
                    hashArr = hash.substring(1);
                    hashArr = hashArr.split(',');
                    window[callback](hashArr);
                }
            }, 250);
        },
        checkWindowSize: function(callback){
            var size = {};
            window.onresize = function(){
                size.width = $(window).width();
                size.height = $(window).height();
                window[callback](size);
            }
        }
    }
}
