var Toyota = {
	init: function() {
		this.addFlash();
		this.usableForms();
		this.overlays();
		this.cycle();
		//this.tabbedProduct();
		this.gallery();
		this.smallGallery();
		this.allGalleries();
		this.used();
		this.colorSwap();
		this.foldMenu();
		this.coolScroll();
		this.newsletter();
		this.promotions();
	},
	coolScroll: function(){
		/*
			jScrollPane for mini footer pics
		*/
		$('#prod-more .banners ul').jScrollPane({
			scrollbarWidth: 12,
			scrollbarMargin: 0,
			showArrows: 1,
			dragMaxHeight: 30
		});
	},
	addFlash: function(){
		/*
			adds flash topbar
		*/
		
		var marked = $('#flash-heading').attr('marked');
                $("#main_flash").flash({
			src:'/webroot/swf/Site.swf',
                        width:'100%',
                        height:'100%',
                        wmode: 'transparent',
                        allowScriptAccess: 'sameDomain',
                        allowFullScren: 'false',
                        bgcolor:'#000000', 
                        flashvars: {
				copyrightsURL:'http://toyota-radosc.pl/artykul/informacje-prawne',
                     		copyrightsTarget:'_self'
                        }
                        
		});
		
		if ( typeof swffit === 'object')
		{
			swffit.fit('main_flash');
		}
		
		$('.non-flash').
			hide().
			next('#flash-heading').
				flash({
					src: '/webroot/swf/topBar.swf',
					width: 986,
					height: 85,
					allowFullScreen: 'false',
					salign: 'lt',
					allowScriptAccess: 'always',
					wmode: 'transparent',
					hasVersion: 10,
					expressInstaller: '/webroot/swf/expressInstaller.swf',
					flashvars: {
					    topMenuPath: '/webroot/xml/topMenu.xml',
					    menuPath: '/webroot/xml/menu.xml',
					    mainURL: '/',
						marked: marked,
						wmode: 'transparent'
					}
				});
		
		$('#bottom_menu').
			find('ul').
				hide().
			end().
			flash({
				src: '/webroot/swf/bottomBar.swf',
				width: 986,
				height: 59,
				allowFullScreen: 'false',
				wmode: 'transparent',
				flashvars: {
					wmode: 'transparent',
     				bottomMenuPath: '/webroot/xml/bottomMenu.xml',
                    bottomMenu2Path: '/webroot/xml/bottomMenu2.xml'
				}
			});
		
	},
	flashMenuOn: function(height){
		if(typeof(height) === 'undefined'){
			$('#flash-heading embed').attr('height', '490px');
		}
		else{
			$('#flash-heading embed').attr('height', height+'px');
		}
	},
	flashMenuOff: function(){
		$('#flash-heading embed').attr('height', '85px');
	},
	overlays: function(){
		/*
			hide elements
		*/
		$('a.iframe').not('.open_new_tab').fancybox({
			overlayOpacity: 0.7,
			overlayColor: "#000",
			type:'iframe',
			autoScale: false,
			autoDimmensions: false,
			width: $(window).width()-10,
			height: $(window).height()-10
		});
		 
		$('a.form').not('.open_new_tab').fancybox({
			overlayOpacity: 0.7,
			overlayColor: "#000",
			onComplete: this.usableForms,
			width: 480,
			autoDimensions: false,
			autoScale: false
		});

		$('a.promotion').not('.open_new_tab').fancybox({
		    scrolling: 'no',
		    height: 750,
		    width: 980,
			overlayOpacity: 0.7,
			autoDimensions: false,
			autoScale: false,
			overlayColor: '#000'
		});

		$('a.configure').not('.open_new_tab').fancybox({
		    width: 950,
			height: 700,
			overlayOpacity: 0.7,
			overlayColor: "#000",
			autoDimensions: false,
			autoScale: false,			
			type: 'iframe'
		});
       
		$('a.accessories').fancybox({
			width: 980,
			height: 700,
			overlayOpacity: 0.7,
			overlayColor: "#000",
			autoDimensions: false,
			autoScale: false,
			type: 'iframe'
		});
        $('a.mc_promo').click(function (ev)
        {
            ev.preventDefault();
            var url = $(this).attr('href') + '/abstract/';
		    $.fancybox({
		        href:url,
			    width: 980,
			    height: 700,
			    overlayOpacity: 0.7,
			    overlayColor: "#000",
			    autoDimensions: false,
			    autoScale: false,
			    type: 'iframe'
		    });            
        });
		//$('li:nth-child(2) a.form').trigger('click');
	},
	usableForms: function(){

		// error tooltips
		$('.overcontent .select li:has(.error-tooltip)').live('mouseover mouseout', function(event){
			if (event.type == 'mouseover') {
				$(this).find('.error-tooltip').show();
			} else {
				$(this).find('.error-tooltip').hide();
			}
		});

		// handler	
		function handle(element, text){
			if(element.attr('value').length === 0)
			{
				element.attr('value', defaultText);
			}
           element.bind('focus', function(){
                   if($(this).attr('value') == text){
                           $(this).attr('value', '');
                   }
           }).bind('blur', function(){
                   if($(this).attr('value') == ''){
                           $(this).attr('value', text);
                   }
           });
                       

		}


		/* overlay */
		function fillInput() {
	   		$('.overcontent input').each(function(){
	   			defaultText = $(this).prev('label').css('display', 'none').text();
	   			handle($(this), defaultText);
	   		});
	       }

		function cleanDefaultInput() {
			$('.overcontent input[type!=checkbox]').each(function(){
				var id = $(this).attr('id');
				defaultText = $('label[for=' + id + ']').text();

				if($(this).attr('value') == defaultText){
					$(this).attr('value', '');
				}
			});
		}

		function addJqTransform() {
			$('div.group').jqTransform();
			$('.disclaimer').jqTransform();
		}


		function bindFormSubmit() { 

			/* datepicker */
			$('input.date').datepicker({
				dateFormat: 'yy-mm-dd',
				regional: 'pl',
				changeMonth: true,
				changeYear: true,
				yearRange: 'c-0:c+01'
			});

			$('input.date_prev').datepicker({
				dateFormat: 'yy-mm-dd',
				regional: 'pl',
				changeMonth: true,
				changeYear: true,
				yearRange: 'c-10:c'
			});

	   		fillInput();
			addJqTransform();

			$.fancybox.resize();

			$('form').bind("submit", function(ev) {
				cleanDefaultInput();
				var actionUrl = $(this).attr('action')
				var serializedArray = $(this).serializeArray();
				
				for(i in serializedArray)
				{
					if(serializedArray[i]['name'] === 'agreement')
					{
						serializedArray[i]['value']='on';
					}
				}
				
				$.fancybox.showActivity();

				$.ajax({
					type    : "POST",
					cache	: false,
					url		: actionUrl,
					data	: serializedArray,
					success : function(data) {
						$.fancybox.hideActivity();
						$.fancybox(data, {
							overlayOpacity: 0.7,
							overlayColor: "#000",
							scrolling: 'yes',
							autoDimensions: true,
							autoScale: false,
							onComplete: function(){
								$('.jqTransformSelectWrapper ul').css('width', '134px');
								function res(){
									$.fancybox.resize();
								}
								setTimeout(res, 1);
							}
						});
						
						bindFormSubmit();
					}
				});
				
				return false;
			});//bind		
		}//
		bindFormSubmit();
	},
	toggleNewsletter: function(url){
		$nws = $('#newsletter');

		if($nws.css('display') == 'none'){
			$nws.fadeIn();
		}
		else{
			$nws.fadeOut();
		}
	},
	cycle: function(){
		/*
			prepare
		*/

		var $slides = $('.rotator .slides');
		var $slidesLi = $slides.find('li');

		$slidesLi.each(function(j){
			j=j+1;
			if(j%3==1){
				$(this).add($(this).next()).add($(this).next().next()).wrapAll('<div>');
			}
		});

		/* 
			bind
		*/

		if($slides.length){
			$slides.cycle({
				timeout: 0,
				prev: $('.rotator .slides-nav .prev a'),
				next: $('.rotator .slides-nav .next a'),
				speed: 500,
				fx: 'scrollHorz',
				easing: 'swing'
			});
		}
	},
	tabbedProduct: function(){
		/*
			Switch between product picture / gallery / colors
		*/
		$('.fake-tabs').tabs('.prod-list > li', {
			effect: 'fade'
		});

		tabApi = $('.fake-tabs').tabs();

		$('.under a:eq(0)').addClass('current');

		function makeCurrent(what){
			// make a current link
			what.parent().parent().find('a').removeClass('current');
			what.addClass('current');
		}

		$('a[href~=#prod-start]').click(function(){
			tabApi.click(0);
			makeCurrent($(this));
			return false;
		});

		$('a[href~=#prod-gallery]').click(function(){
			tabApi.click(1);
			makeCurrent($(this));
			return false;
		});

		$('a[href~=#prod-colors]').click(function(){
			tabApi.click(2);
			makeCurrent($(this));
			return false;
		});
	},
	gallery: function(){
		/*
			Gallery
		*/
		
		$('.next a,.prev a').click(function(){
			return false;
		});


		var pic = $('#prod-gallery .pic');
		var galleryType = 1; // 1 - big, 2 - small (used cars)
                
		if($('#used .pic').attr('class')){
			//pic = $('#used .pic');
			galleryType = 2;
			enlarge = $('.gallery-tools .enl a');
		}
		pic.find('img').attr('data-id', 0);


		function addNewImg(src){
			pic.append('<img src="'+src+'" alt="" style="display: none"/>');
		}

		gl = $('#prod-gallery .gallery-list');

		function load(index){
			if(index < 0 || index >= gl.find('li').length){
				return false;
			}
			gl.find('a').removeClass('current');
			gl.find('a:eq('+index+')').addClass('current');
            linkNode  = gl.find('a:eq('+index+')');
			newImg = linkNode.attr('href');
            previewImg = linkNode.attr('preview'); 
			pic.find('img').fadeOut(200, function(){
				$(this).remove();
				pic.find('img[data-id='+index+']').remove();
				addNewImg(previewImg);
				pic.find('img').fadeIn(400).attr('data-id', index);
				//$('.gallery-tools .dl a').attr('href','/download/'+newImg.split('/').pop());
                $('.gallery-tools .dl a').attr('href',newImg).attr('target', '_blank');
			});

			if(galleryType == 2){
                                enlarge.attr('href', newImg);
			}
			return true;
		}

		if(galleryType==1){
			var galSize = 6;
		}
		else{
			var galSize = 4;
		}	

		$('#prod-gallery .gallery-list').scrollable({
			size: galSize,
			nextPage: '.next a',
			prevPage: '.prev a'
		});

		x = $('#prod-gallery .gallery-list').data('scrollable');

		$('#prod-gallery .gallery-list a').click(function(){
			load($('#prod-gallery .gallery-list a').index(this));

			return false;
		});

		$('#prod-gallery .gallery-tools .nextPic a').click(function(){
            var nindex = parseInt(pic.find('img').attr('data-id'))+1;
            var pindex = parseInt(pic.find('img').attr('data-id'));
			if( load(nindex) ){
				//x.move(1);
				x.next();
			}
			return false;
		});

		$('#prod-gallery .gallery-tools .prevPic a').click(function(){
            var pindex = parseInt(pic.find('img').attr('data-id'))-1;
            var nindex = parseInt(pic.find('img').attr('data-id'));
			if( load(pindex) ){
				//x.move(-1);
				x.prev();
			}
			return false;
		});


		$('#prod-gallery .gallery-list-nav .next a').click(function(){
            var nindex = parseInt(pic.find('img').attr('data-id'))+galSize;
            var pindex = parseInt(pic.find('img').attr('data-id'));
				x.move(galSize);
			return false;
		});

		$('#prod-gallery .gallery-list-nav .prev a').click(function(){
            var pindex = parseInt(pic.find('img').attr('data-id'))-galSize;
            var nindex = parseInt(pic.find('img').attr('data-id'));
		x.move(-1*galSize);
		
			return false;
		});

		$('.gallery-tools .enl a').fancybox({type: 'image'});
		load(0); // initial load
	},
	smallGallery: function(){
		/*
			Small gallery
		*/
		
		var $sg = $('.small-gallery'); // cache
        var $thumbs =  $sg.find('.thumbs');
		// scrollable right-hand thumbs
		$thumbs.scrollable({
			size: 4,
			next: '.thumbs .nav .next a',
			prev: '.thumbs .nav .prev a',
			vertical: true,
			clickable: true
		});
		
		// js api
		sapi = $thumbs.data('scrollable');
		if(sapi){
		// initial setup
		$sg.
			find('.pages .of').
				text($(".itemscontainer img").length).
			end().
			find('.pages .page')
				.text('1');
		}
		// helper that loads a big picture
		var loadPhoto = function(url, $_this){
			
			$sg.find('.picture img').fadeOut(500, function(){
				$(this).remove();

				// replace image
				$sg.find('.picture img').remove();
				$sg.find('.picture').
					append('<img src="'+url+'" alt="" style="display: none;"/>');
				$sg.find('.picture img').fadeIn(500);

				// update counter
				$sg.
					find('.pages .page').
						text($('.thumbs .items img').index
($_this)+1);
						
				// current element
				$_this.parent().parent().find('li').removeClass('current').end().end().addClass('current');
			})
		};
		

        
       $sg.find(".big .next a").click(function(e){
            var index = $('.items img').index($('.items .currentimage'))+1;
            var $next = $($sg.find('.items img')[index]);
            var page = index/4;
            sapi.seekTo(page);
            if ($next.length >  0) {
                $next.click();
            }
        });

        $sg.find(".big .prev a").click(function(e){
            var index = $('.items img').index($('.items .currentimage'))-1;
            var $prev = $($sg.find('.items img')[index]);
            var page = index/4;
            sapi.seekTo(page);
            if($prev){
                $prev.click();
            }
            else
            {                
                $($sg.find('.items img')[0]).click();
            }
         });
	$(".itemscontainer img").click(function(e){
                $('.itemscontainer img').removeClass('currentimage');
		loadPhoto($(this).attr('rel'), $(this));
                 $(this).addClass('currentimage');
           });	
	},
	allGalleries: function(){
		// all galleries list hovers
		
		var $ag = $('.all-galleries');
		if($ag.length){
			$ag.find('.pic a').add('span.more').css('opacity', 0);

			$ag.find('.pic').hover(function(){
				$(this).
					find('span.more').
						animate({
							opacity: 0.8
						}, 300).
					end().
					find('a').
						animate({
							opacity: 1
						}, 400);
			}, function(){
				$(this).
					find('span.more, a').
						animate({
							opacity: 0.0
						}, 200);
			});
		}
	},
    showForm:function(url)
    {
	    $.fancybox({
			href: url,
			width: 980,
			height: 700,
			overlayOpacity: 0.7,
			overlayColor: "#000",
			type: 'iframe'
	    });
    },
	used: function(){
		/*
			used-items big picture cloud
		*/
		$('.used-items .mini a').hover(function(){
			$(this).parent().find('.big').fadeIn(150);
		}, function(){
			$(this).parent().find('.big').fadeOut(350);
		});

		/*
			used-list sorter roll-down
			pos:abs & overflow
		*/
		$('.used-list .sort li').hover(function(){
			$(this).parent().css('overflow', 'visible');
		}, function(){
			$(this).parent().css('overflow', 'hidden');
		});
		/*
           setting current selected position as first to display
		*/
		$('.used-list .sort ul').prepend($('.used-list .sort .sortselected'));
	},
	colorSwap: function(){
		/*
			Browse color variants
		*/
		var $prodColors = $('#prod-colors');
		
		// check for $prodColors existence
		if(!$prodColors.length)
			return false;

		var $pic = $prodColors.find('.pic');
		

        // initial imgage
		var $first_pic = $('#prod-colors .color-list').find('li:eq(0) a');
		$pic.find('img').attr('src', $first_pic.attr('href'));
		$prodColors.find('.color-list h3 em').text($first_pic.find('img').attr('alt')).show();
		

        function showImage($context){
			var href = $context.attr('href');
			var $img = $pic.find('img');
			
			if($img.attr('src') != href){
				$pic.find("img").remove();
				$pic.
					append("<img style='display: none'>").
						find('img').
						attr('src', href).
						fadeIn(800);
			}
			
			$prodColors.
				find('.color-list h3 em').
					text($context.find('img').attr('alt'));
				
			
        }

		$('#prod-colors .color-list a').
			mouseover(function(){
				showImage($(this));
			}).
			mouseout(function(){
				return false;
			}).click(function(){
				return false;
			});
	},
	foldMenu: function(){
		/*
			Left side menu & submenu
		*/
		$('#secondary .side-nav').find('li:not(.current) ul').hide();
	},
	newsletter: function(){
        var $newsletter = $('#newsletter');
        var $form = $newsletter.find("form");
        var $submit = $newsletter.find("submit");
        var $signout = $newsletter.find(".signout");
		var self = this;
        
		$newsletter.find('.close a').live('click', function(){
			self.toggleNewsletter();
			return false;
		});

		$form.unbind("submit");
        $form.bind('submit', function(e){
                e.preventDefault();
                var email = $newsletter.find("input[name='email']").val();
                $.post('/newsletter/save/', {
                        email:email
                }, function(response){
                    var $message = $newsletter.find(".message");
                    if(response['newsletter_status'] == 'OK')
                    {
                        $newsletter.html('<div class="message"><p class="confirmation">Dziękujemy. Przyjęliśmy zamówienie na newsletter.<br>Na podany adres e-mail wysłaliśmy wiadomość w celu potwierdzenia zamówienia. Prosimy o sprawdzenie swojej poczty.</p><p class="close"><a href="">zamknij</a></p></div>');
						setTimeout("Toyota.toggleNewsletter()", 10000);
                    }
                    else
                    {
                        $message.text(response['newsletter_error_message']);
                    }
               }, "json");
        });

        $signout.click(function(e){
            e.preventDefault();
            var email = $newsletter.find("input[name='email']").val();
            $.post('/newsletter/remove/', {
                    email:email
            }, function(response){
                    var $message = $newsletter.find(".message");
                    if(response['newsletter_status']=='OK')
                    {
                        $message.text('Twój email został usunięty z naszej bazy danych');
						setTimeout("Toyota.toggleNewsletter()", 10000);
                    }
                    else
                    {
                        $message.text('Ten email nie istnieje w naszej bazie danych');
                    }
            },"json");
        });
       
    },
    redirect: function(){
        var qs = new Querystring();
        var func_name = qs.get('func_name');
        var allowed_func = { 
            'flash_popup':true,
            'flash_route':true,
            'flash_form':true        
        };
        var url = qs.get('url');
        if (allowed_func[func_name]){
           $(function(){
            eval(func_name+'(\''+ encodeURI(url) +'\')');
            });
        }
    
    
    }, 
    promotions: function(){
        var $selected_promotion = $(".selected_promotion");
        if($selected_promotion.length > 0)
        {
            $(window).scrollTop($selected_promotion.offset().top);
        }
    }
};

$(document).ready(function(){
	Toyota.init();
});



