var dppw = {
    msg: {
        pl: {
            invalidFormat: "Nieprawidłowy format adresu e-mail",
            fillInRequired: "Wypełnij poprawnie wymagane pola",
            iemsg: {
                h: 'Używasz Internet Explorera?',
                msg: '<p>Być może jeszcze o tym nie wiesz ale to nienajlepszy wybór.</p><p>Dla Ciebie najważniejszy jest fakt, że ta przeglądarka <em>może narazić Twój komputer na niebezpieczeństwo</em>.</p> <p>Kwestia ważna dla nas to to, że IE bardzo słabo radzi sobie z nowoczesnymi technologiami, a z nich właśnie korzystamy wykonując projekty dla naszych klientów.</p> <p>Jeżeli chcesz cieszyć się wszystkimi możliwościami tej i wielu innych stron internetowych, <a href="http://browsehappy.pl/" title="Zmień przeglądarkę na bezpieczniejszą i nowocześniejszą!">zainstaluj dobrą przeglądarkę</a>. Wszyscy na tym skorzystamy.</p>',
                cl: 'Nie pokazuj więcej tej wiadomości'
            }
        },
        en: {
            invalidFormat: "Invalid e-mail format",
            fillInRequired: "All fields are required",
            iemsg: {
                h: 'Internet Explorer user?',
                msg: '<p>You probably don&rsquo;t know it yet, but using IE is not the best choice.</p><p>The most important thing for you is that this browser can <em>make your computer unsafe</em>.</p> <p>The main issue for us is the fact that IE doesn&rsquo;t support modern web technologies, which we use in our websites.</p> <p>If you want to use the full potential of this and many other websites, <a href="http://browsehappy.com/browsers/" title="Change your browser for better and safer">install modern browser</a>. Everyone will get in on it.</p>',
                cl: 'Don&rsquo;t show this message again'
            }
        }
    },
    init: function() {
        // Google Analytics
        this.googleStats()
        
        this.newsletterSubmit()
        this.resetFieldContent()
        
        // IE msg
        if( $.browser.msie  && ($.browser.version == '6.0' || $.browser.version == '7.0') && 
            ($('body').is('#dapperweb-home') || $('body').is('#dapperweb-contact')) ) { 
                this.ie() 
        }
        
        this.flagsHover()
        
        if ($('body#dapperweb-home').length) { this.footerFlash() }
    },
    
    googleStats: function () {
        var GAID = 'UA-7263970-2';
        var head = document.getElementsByTagName('head')[0];
        var scr = document.createElement('script');
        scr.type = 'text/javascript';
        scr.src = (location.protocol == 'http:' ? 'http://www.' : 'https://ssl.') + 'google-analytics.com/'+'ga.js';
        var once = 0;
            function runMe() { 
                    if (scr.readyState == 'loading' || _gat == undefined || once) { return; }
                    clearInterval(timer);
                    once++;

                    var pageTracker = _gat._getTracker(GAID);
                    pageTracker._initData();
                    pageTracker._trackPageview();
            }
        var timer = setInterval(runMe, 2000);
        scr['onload'] = runMe;
        scr['onreadystatechange'] = runMe;
        head.appendChild(scr);
    }, 
    
    newsletterSubmit: function() {
        var $loader,
            $msg = $('<p class="message"></p>');

        if (dppw.lang == 'pl') {
        	$loader = $('<div class="ajax-loader"><img src="i/ajax-loader.gif" alt="Loading..." /></div>')
        } else {
            $loader = $('<div class="ajax-loader"><img src="../i/ajax-loader.gif" alt="Loading..." /></div>')
        }
            
            
        $('#newsletter :submit').wrap('<div class="submit-wrap"></div>').parent()
            .append($loader, $msg)
            .find('.ajax-loader, .message').hide()
            
        $('#newsletter form').submit(function(){
            $msg.hide()
            $loader.hide().fadeIn('fast')
                
            $.ajax({
                type: 'post',
                url: 'newsletter.php',
                data: 'email=' + $('#newsletter-email').val(),
                dataType: 'json',
                success: function(data) {
                    if (data.status == 'error') {
                        if (data.msg) {
                            $loader.fadeOut('fast', function() {
                                $msg.text(data.msg).fadeIn('fast');
                            });
                        }
                    } else if (data.status == 'ok') {
                        $loader.fadeOut('fast', function() {
                            if (data.msg) {
                                $loader.fadeOut('fast', function() {
                                    $msg.text(data.msg).fadeIn('fast');
                                    setTimeout(function () {
                                        $msg.fadeOut('fast')
                                        
                                         $('#newsletter-email').trigger('focus').trigger('blur')
                                    }, 2500)
                                });
                            }
                        });
                    }
                }
            });
            return false;
        });
    },
    
    resetFieldContent: function() {
        $('form :text').each(function(){
            $(this)
                .focus(function() { if (this.value == this.defaultValue) { this.value = '' } })
                .blur(function(){
                    if (this.value == this.defaultValue || this.value == '') { this.value = this.defaultValue }
                    if ($.browser.msie && $.browser.version == '7.0') { $(this).parent().removeFilter() }
                })
        });
    },
    
    ie: function() {
        if(document.cookie.indexOf("dppw-ie-message") == -1) {
            $('#wrap').css('position', 'relative');
            
            var $helloie = $("<div id='ie-msg'></div>")
                .append('<p id="ie-intro">' + dppw.msg[dppw.lang].iemsg.h + '</p>')
                .append('<div id="ie-content">' + dppw.msg[dppw.lang].iemsg.msg + '<a href="#" id="ie-close">' + dppw.msg[dppw.lang].iemsg.cl + '</a></div>');
            
            $helloie
                .animate({'opacity': 0.6}, 250, function() { $('#ie-intro').animate({'width': 0}, 450) })
                .find('#ie-intro')
                    .click(function(){
                        if (!$('#ie-content').hasClass('msgVisible')) 
                            { $('#ie-content').slideDown(450).addClass('msgVisible') } 
                        else 
                            { $('#ie-content').slideUp(450).removeClass('msgVisible') }
                    })
                    .hover(
                        function(){ $(this).css('textDecoration', 'underline') }, 
                        function(){ $(this).css('textDecoration', 'none') }
                    )
                    .end()
                .find('#ie-content').hide().end()
                .hover(
                    function(){
                        $(this)
                            .stop().animate({'opacity': 0.9}, 400)
                            .find('#ie-intro').stop().animate({'width': 260}, 400)
                    }, 
                    function(){
                        $(this)
                            .stop().animate({'opacity': 0.5}, 450)
                            .find('#ie-content').stop().slideUp(450, function() {
                                $helloie.find('#ie-intro').stop().animate({'width': 0}, 450)
                            }).removeClass('msgVisible')
                    }
                )
                .find('#ie-close').click(function(){					
                    $helloie.fadeOut(450, function() {
                        $(this).remove()
                    })

                    var ttl =  new Date();
                    ttl.setTime(ttl.getTime()+1000*60*60*24*30);
                    document.cookie="dppw-ie-message=true;expires=" + ttl.toGMTString();
                    
                    return false;
                });
            
            $("#wrap").prepend($helloie);
        };
    },
    
    flagsHover: function() {
        $('#lang a').not('.active').animate({opacity: 0.5}, 0)
        
    	$('#lang a').hover(function(){
    		$(this).stop().animate({opacity: 1}, 300)
    	}, function(){
    		$(this).not('.active').stop().animate({opacity: 0.5}, 300)
    	});
    },
    
    footerFlash: function() {
        var p;
        dppw.lang == 'en' ?  p = '../' : p = ''
    
        $('#about').append('<div id="rFlash" />');		
        $('#about #rFlash').flash({
            src: p + 'flash/baza.swf',
            width: 475,
            height: 193
        })

    }
}


$(document).ready(function(){
    $('body').addClass('js');
    dppw.init()
    
    var path = '';
    if (dppw.lang == 'en') {
    	path = '../'
    }
    
    jQuery.fn.extend({
		// msie7 ClearType bug
		removeFilter: function() {
			return this.each(function(){
				if(this.style.filter && this.style.removeAttribute){
					this.style.removeAttribute('filter');
				}
			});
		},
        
        showWarning: function(text) {
        	return this.each(function(){
                var $form = $(this).parents('form');
                
        		$(this).next('div.required-icon').addClass('error').fadeIn('fast', function() {
        			$('p.message', $form).text(text).fadeIn('fast')
        		})
        	});
        },
        
        hideWarning: function() {
        	return this.each(function(){
                var $form = $(this).parents('form');
            
        		$(this).next('div.required-icon').removeClass('error').fadeOut('fast', function() {
        			if (!$('div.error').length) {
        				$('p.message', $form).fadeOut('fast')
        			}
        		})
        	});
        },
        
        required: function() {
        	return this.each(function(){
        		$(this).keyup(function(){
        			if (!this.value) {
            			$(this).showWarning(dppw.msg[dppw.lang].fillInRequired)
            		} else {
                        $(this).hideWarning()
                    }
        		}).blur(function(){
        			if (!this.value) {
            			$(this).showWarning(dppw.msg[dppw.lang].fillInRequired);
            		} else {
                        $(this).hideWarning()
                    }
        		})
        	});
        },
        
        markAsActive: function() {
        	return this.each(function(){
        		$('#content div.categories-wrap a.active').removeClass('active').css('opacity', 1);
                $(this).addClass('active')
        	});
        },
        
		setupThumbs: function() {
			return this.each(function(index){
				$('a:first', this).append('<span />')
				
				var animation = 0,
					descTop = '-10px',        
					$span = $('a span', this).css('opacity', 0),
					$desc = $('.description', this).css({ 'margin-top': descTop, 'opacity': 0 });
					
				$(this).hover(function(){
					if (!animation) {
						animation = 1;
						$desc.animate({'marginTop': 0, 'opacity': 1}, 400);
						$span.animate({'opacity': 0.8}, 400)
					}
				}, function(){
					setTimeout(function() {
						$desc.animate({'marginTop': '6px', 'opacity': 0}, 350, function() {
							$(this).css('margin-top', descTop);
						});
						$span.animate({'opacity': 0}, 300, function() { animation = 0; })
					}, 100)
				});
				
		        $(this)
                    .not('.more')
					.click(function(){ $('a', this).trigger('click') })
					.find('a').fancybox({ 
			            'hideOnContentClick': true,
			            'overlayShow': true,
			            'overlayOpacity': 0.7
					})
				
				if ((index + 1) % 3 == 0) { $(this).css('marginRight', '0') }
			});
		}
	})

	
    if (!$.browser.msie) {
        $('form div.text-wrap, form div.textarea-wrap').css('opacity', 0.6);
        
    	$('form div.text-wrap input, form div.textarea-wrap textarea').focus(function() {
    		$(this).parent().animate({'opacity': 1}, 150)
    	}).blur(function(){
    		$(this).parent().animate({'opacity': 0.6}, 150)
           
            
            if ($(this).val() == '') { $(this).addClass('error') } else { $(this).removeClass('error') }
    	})
    }
	
	if ($.browser.msie) {
	    $('#footer input').focus(function() {
	    	$(this).parent().animate({'opacity': 1}, 150)
	    }).blur(function(){
	    	$(this).parent().animate({'opacity': 0.6}, 150)
			
            if ($.browser.msie && $.browser.version == '7.0') { $(this).parent().removeFilter() }
	    })
	}
	
	
	$('.textarea-wrap, .text-wrap').click(function(){ $('input, textarea', this).focus() });
	
	$('input.submit').hover(
		function(){ $(this).css('backgroundPosition', '0 0') }, 
		function(){ $(this).css('backgroundPosition', '0 -44px') }
	);
	
	
    /* contact form */  
    
    $('#contact-form :submit').after('<p class="message">').next('p.message').hide();
    $('#contact-form :text, #contact-form textarea').each(function(){
    	$(this).parent().css('position', 'relative').append('<div class="required-icon"></div>')
    });
    
    $('#contact-form :text, #contact-form textarea').required();
    
    $('#contact-form :submit')
        .after('<div class="ajax-loader"><img src="' + path + 'i/ajax-loader.gif" alt="Loading..." /></div>')
        .next('div.ajax-loader') .hide();
    
    $('#contact-form').submit(function(){
        var $form = this;
        
        // check for errors
        $(':input, textarea', this).each(function() {
        	if (!this.value) {  
        		$(this).parent().css('position', 'relative').end().showWarning(dppw.msg[dppw.lang].fillInRequired);
        	} else {
                $(this).next('.required-icon').fadeOut('fast')
            }
        });
        
        // if errors
        if ($('#contact-form div.error').length) {
            $('div.ajax-loader', $form).fadeOut('fast')
        	$('p.message', $form).html(dppw.msg[dppw.lang].fillInRequired);
        } else {
            // hide message, show ajax-loader
            $('p.message', $form).fadeOut('fast', function() {
                $('div.ajax-loader', $form).fadeIn('fast')
            });

            // use ajax to submit form and display response
            $.ajax({
                type: 'post',
                url: 'sendMessage.php',
                data: 'name=' + $('#name', $form).val() + '&email=' + $('#email', $form).val() + '&message=' + $('#message', $form).val(),
                
                success: function(response) {
                    $('div.ajax-loader', $form).fadeOut('fast', function() {
                        $('p.message', $form).html(response).fadeIn('fast')
                    })
                }
            });
        }
        return false;
    });
    
    
    /*
            client area form
        */
	if ($('body').is('#dapperweb-client')) {
		$('div.checkbox-wrap').each(function(){
			var box = $('a.checkbox', this);
			
			$(' a.checkbox, span.pseudo-label', this)
				.toggle(
					function(){
						box.addClass('checked');
						return false;
					},
					function(){
						box.removeClass('checked');
						return false;
					}
				)
				.click(function(){
					if (box.is('.checked')) {
						var pNo = $(this).parents('.checkbox-wrap').find('.pseudo-label em').text()
						
						$('#client-contact-form #client-accept').val(pNo.substr(0,1))
					} else {
						$('#client-contact-form #client-accept').val('0')
					}
				})
				.hover(
					function(){ box.addClass('hover') }, 
					function(){ box.removeClass('hover') }
				);
		});
		
		
		$('#client-contact-form :submit')
			.after('<p class="message">').next('p.message').hide()
	        .after('<div class="ajax-loader"><img src="i/ajax-loader.gif" alt="Loading..." /></div>')
	        .next('div.ajax-loader')
	            .hide();
		
		$('#client-contact-form').submit(function(){			
			var $form = $(this);
			
            $('p.message', $form).fadeOut('fast', function() {
                $('div.ajax-loader', $form).fadeIn('fast')
            });
		
			// use ajax to submit form and display response
			$.ajax({
				type: 'post',
				url: 'client-sendMessage.php',
				data: 'client-name=' + $('#client-name').val() + '&client-email=' + $('#client-email').val() + '&client-message=' + $('#client-message').val() + '&client-fullname=' + $('#client-fullname').val(),
				
				success: function(response) {
					$('div.ajax-loader', $form).fadeOut('fast', function() {
						$('p.message', $form).html(response).fadeIn('fast')
					})
				}
			});
			return false;
		});
	}

    /* register user form */
    $('#register-user').submit(function(){
		var $form = this;
		$('p.message', $form).remove();
		
		$(':submit', $form).next('.ajax-loader').remove().end().after('<div class="ajax-loader"><img src="i/ajax-loader.gif" alt="Loading..." /></div>')
		$.ajax({
			type: 'post',
			url: 'registeruser.php	',
			data: 'username=' + $('#username').val() + '&fullname=' + $('#fullname').val() + '&email=' + $('#email').val() + '&password=' + $('#password').val() + '&c_password=' + $('#c_password').val(),
			
			success: function(results) {
				$('div.ajax-loader', $form).fadeOut('fast', function() { 
					$(this).remove(); 
					$('fieldset', $form).append('<p class="message"></p>').find('.message').text(results)
				})
			}
		});
		
		return false;
	});


    /*  portfolio  */
    
	if ($('body#dapperweb-portfolio .thumbs-wrap').length || $('#dapperweb-client .thumbs-wrap').length) {
		var $ajaxloader = $('<div class="ajax-loader"><img alt="Loading..." src="/i/ajax-loader.gif"/></div>').hide();
	
		if ($.browser.msie && $.browser.version == '6.0' || $.browser.version == '7.0') {
		    $('<script type="text/javascript" src="' + path + 'fancybox/jquery.pngFix.pack.js"></script>').appendTo('head')
			
			var $ajaxloader = $('<div class="ajax-loader"></div>').hide();
		}
		
		var settings = { liWidth: 829 }
		
		function fadeInImgs() {
			$('.thumb img').css('opacity', 0).each(function(){
				if (this.complete || this.readyState == 'complete') { $(this).animate({'opacity': 1}, 300) } 
				else { $(this).load(function() { $(this).animate({'opacity': 1}, 300) }); }
			});
		}
		fadeInImgs();
		
		// setup thumbs behaviour
		$('div.thumb').setupThumbs();

		function pager() {
			var $ul = $('.thumbs-wrap'),
                liCount = $(' > li', $ul).length;
			
	        $ul
				.wrap('<div id="thumbs-wrap-out">')
				.css({ 'width': liCount * settings.liWidth + 'px' })
				.parent().append($ajaxloader);
				
			if ($(' > li', $ul).length > 1) {
		        $(' > li', $ul).each(function(index){
		            var no = index + 1
		        	$(this).attr('id', 'li' + no)
		        });
				
				if(!$('ul.pager').length) {
					var $pager = $('<ul class="pager"/>').appendTo('#portfolio-nav li.active').hide(); 
				}

				function newItem(id) {
					return $('<li><a href="#' + id + '">' + id.substr(2) + '</a></li>').appendTo('.pager');
				}
				
				$(' > li', $ul)
					.each(function(){
						var navItem = newItem($(this).attr('id'));
						
						navItem.children('a:eq(0)').click(function(){
							var id = $(this).attr('href').split('#')[1];
							var difference = $ul.offset().left-$('> li#' + id, $ul).offset().left;
							$ul.animate({left: difference}, 700);
							
							$(this).parents('ul.pager').find('li.active').removeClass('active')
							$(this).parent().addClass('active');
							return false;
						});
					});
					
					var navLen = $('.pager li').length * 34 + 'px';
					$('.pager').css('width', navLen).find('li:first').addClass('active')
					
					$pager.slideDown(400)
			}
		}
		pager();
		
		function updateH2(title) { $('#content h2 em').text(title) };
		
		function portfolioAjaxLoad(){
			$('#portfolio-nav .portfolio-category').unbind('click', portfolioAjaxLoad)
			
			if (!($.browser.msie && $.browser.version == '6.0')) {
			    $ajaxloader.fadeIn(400);
			} else { $ajaxloader.show(); }
			
			var link = $(this),
				href = $(this).attr('href');
				
			$('<div id="temp-container" />')
				.insertAfter('#thumbs-wrap-out')
				.hide()
				.load(href + ' ul.thumbs-wrap', function() {
					$('div.thumb').setupThumbs();
					link.parent().addClass('active').siblings('.active').removeClass('active');
					
					$('#portfolio-nav .pager').slideUp(400, function() { 
						$(this).remove() 
					})
					
						$('#thumbs-wrap-out').fadeOut(400, function() {
							$(this).empty()
                            
							$('#temp-container .thumbs-wrap').hide().appendTo('#thumbs-wrap-out').show()
                            $('#temp-container').remove()
                            
							updateH2(link.text())
							pager();
                            
                            $(this).fadeIn(400)
						})
					
					if (!($.browser.msie && $.browser.version == '6.0')) {
						setTimeout(function () { $ajaxloader.fadeOut(400) }, 300)
					} else { setTimeout(function () { $ajaxloader.hide() }, 300) }
				})
				
				$('#portfolio-nav .portfolio-category').bind('click', portfolioAjaxLoad)
				return false;
		}
		$('#portfolio-nav .portfolio-category').bind('click', portfolioAjaxLoad);
	}
	
	
	// client area gallery
	if ($('div.client-content').length) {
		var settings = {
			ul: '.thumbs-wrap',
			liWidth: 358
		}
		var $ul = $(settings.ul);
		$ul.css('width', settings.liWidth)
		
		
		function clientPager() {
			$ul = $(settings.ul);
			liCount = $(' > li', $ul).length,
			
	        $ul
				.css({ 'width': liCount * settings.liWidth + 'px' })
				.parent().append($ajaxloader);
				
			if ($(' > li', $ul).length > 1) {
		        $(' > li', $ul).each(function(index){
		            var no = index + 1
		        	$(this).attr('id', 'li' + no)
		        });
				
				if(!$('ul.pager').length) {
					var $pager = $('<ul class="pager"/>').appendTo('#client-thumbs'); 
				}

				function newItem(id) {
					return $('<li><a href="#' + id + '">' + id.substr(2) + '</a></li>').appendTo('.pager');
				}
				
				$(' > li', $ul)
					.each(function(){
						var navItem = newItem($(this).attr('id'));
						
						navItem.children('a:eq(0)').click(function(){
							var id = $(this).attr('href').split('#')[1];
							var difference = $ul.offset().left-$('> li#' + id, $ul).offset().left;

							$ul.animate({left: difference}, 600);
							
							$(this).parents('ul.pager').find('li.active').removeClass('active')
							
							$(this)
								.parent().addClass('active')
								.parents('#client-thumbs').find('.pseudo-label em').text($(this).text() + '.')
							return false;
						});
					});

					$('.pager li:first')
						.addClass('active')
						.parents('#client-thumbs').find('.pseudo-label em').text($('li.active a').text() + '.')
			}
		}
		clientPager();
	}	
});