var sbPrintLabel = '';
 var sbBackLabel = 'Ger&#304;';
 var sbPreviousLabel = 'Önceki';
 var sbNextLabel = 'Sonraki';
 var sbWatchVideoLabel = 'VIDEO IZLE';
 var sbLofiCloseLabel = 'KAPAT';
 var sbLofiFullviewCloseLabel = 'TAM EKRANI KAPAT';
 var sbGalleryWallpaperLabel = 'DUVAR KAGITLARI';
 var sbVideosLabel = '${sbVideosLabel}';


//Helper functions
function supports_isSafari() { // Check for Safari 5 or greater
    var userAgent = navigator.userAgent.toString().toLowerCase();
    if ((userAgent.indexOf('safari') != -1) && !(userAgent.indexOf('chrome') != -1) && ($.browser.version >= "533")) {
        return true
    }
}

function supports_video() { // Check HTML5 support
    return !!document.createElement('video').canPlayType;
}

function supports_h264() { // Check H264 codec support
    if (!supports_video()) {
        return false;
    }
    var v = document.createElement("video");
    return v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"');
}

function loadTemplate() { 
   if (supports_h264() || supports_isSafari()) {
		var url = "/static/video-template-html5.html"; //Check if H264 support and Safari > 5
	} else {
		var url = "/static/video-template.html";
	}
	return url;
}

/*function supports_android() {
	$('video').click(function(index) {
			alert($('video'));
			alert(index);
			this.play();
	});
}*/

function endsWith(str, suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
}

//JavaScript templating engine functions
(function ($) {
	$.nano = function (template, data) {
		return template.replace(/\{([\w\.]*)\}/g, function (str, key) {
			var keys = key.split("."),
				value = data[keys.shift()];
			$.each(keys, function () {
				value = value[this];
			});
			return (value === null || value === undefined) ? "" : value;
		});
	};
})(jQuery);





$(document).ready(function () {
							
							

    $('body').addClass('hasJS');

    px = 'px';

    // function makes the whole LI clickable (if all the links inside point to the same URL)
    $.fn.clickable = function () {
        LIs = $(this).children('li');

        LIs.addClass('clickable').click(function () {
            window.location = $(this).find("a").attr("href");
            return false
        });

        for (i = 0; i < LIs.length; i++) {
            links = $(LIs[i]).find('a');
            $links = links;

            for (j = 1; j < links.length; j++) {
                if ($(links[0]).attr('href') !== $(links[j]).attr('href')) {
                    $(LIs[i]).removeClass('clickable').unbind('click');
                    break
                };
            };

        };
    }

    // setting up carousel
    $.fn.Carousel = function (thumbWidth, speed) {

        speed = speed
        theCarousel = this;

        thumbN = 2;
        total = $(this).children('li').length;

        // adding wrapper and previous/next arrows
        $(this).wrap('<div class="carousel">').wrap('<div class="carousel_inner">');
        $('<a href="#" class="prev">' + sbPreviousLabel + '</a>').addClass('disabled').click(function () {
            slide('left', speed);
            return false
        }).prependTo('.carousel');
        $('<a href="#" class="next">' + sbNextLabel + '</a>').click(function () {
            slide('right', speed);
            return false
        }).appendTo('.carousel');

        thumbWidth = $(this).find('>li').outerWidth();
        visiblePart = thumbWidth * thumbN; // carousel width
        totalWidth = thumbWidth * total; // total carousel width (all thumbnails)
        leftIndent = 0;

    };

    // carousel


    function slide(where, speed) {
        if (where == 'right') {
            if (totalWidth + leftIndent > visiblePart) leftIndent -= visiblePart;
        }
        else {
            if (leftIndent < 0) leftIndent += visiblePart;
        }

        //animating carousel and then disabling arrows if necessary
        $(theCarousel).animate({
            'left': leftIndent
        }, speed, function () {
            DisAble();
        });
    };

    //disabling arrows


    function DisAble() {
        if (totalWidth + leftIndent <= visiblePart) $('.carousel .next').addClass('disabled');
        else $('.carousel .next').removeClass('disabled');

        if (leftIndent == 0) $('.carousel .prev').addClass('disabled');
        else $('.carousel .prev').removeClass('disabled');
    }

    function pauseVideo() { //Pause video to stop multiple playback
        if ($('video')) {
            $('video').each(function (index) {
                $('video')[index].pause();
            });

        }
    }

    // function overview gallery
    $.fn.overviewGallery = function () {
        $(this).find('.slide:not(:first)').hide();

        var slide = $(this).find('.slide');
        var total = slide.length;
        var current = 0;

        $('.gallery-nav a').click(function (e) {

            if ($(this).is('.next')) {
                current++;
            } else {
                current--;
            };

            if (current == total) {
                current = 0
            };
            if (current == -1) {
                current = total - 1
            };

            $('.slide:visible object').hide();
            $('.slide:visible video').hide();
            $('.slide:visible').fadeOut();
			
			//IE fix to stop quicktime videos playing at the same time
			//var removeSlide = $('.slide:visible'); // select current slide to remove
			//console.log($('.slide:visible'));
			//removeSlide.detach(); //remove slide from the DOM (Stops IE playing quicktime)
			//$('.overview-gallery').append(removeSlide); //append slide back to the DOM

            $(slide[current]).fadeIn(function () {
                $(slide[current]).find('object').show();
                $(slide[current]).find('video').show();
            });
            $('.gallery-nav strong').text(current + 1 + ' of ' + total);

            pauseVideo(); //pause video 
            return false;
        });
    }

    // /function overview gallery
    //overview slides	
    loadOverviewXML = function (xmlUrl) {
        $.ajax({
            type: "GET",
            url: xmlUrl,
            dataType: "xml",
            success: function (xml) {
                var videoURL = []; //video urls for ipad bug
				var templateUrl = loadTemplate(); //call template function
                var templateHTML = $.ajax({ //load external video template
                        type: "GET",
                        url: templateUrl, //template url returned by loadTemplate function
                        async: false
                	}).responseText; //Output the video template markup
				var newHTML = '<div class="overview-gallery">';
				
                $(xml).find('slide').each(function () {
                    var title = $(this).find('title').text();
                    var bodytext = $(this).find('bodytext').text();
                    var assetUrl = $(this).find('assetUrl').text();
                    var linkToLabel = $(this).find('linkToLabel').text();
                    var linkToUrl = $(this).find('linkToUrl').text();
					var posterImage = $(this).find('stillImageUrl').text();
                    
					var type = $(this).attr("type");
					if (type == "video" || type == "nameplateVideo")
						if (endsWith(assetUrl, '.mp4')) { //If video type and .mp4
							var data = { //Provide video data for templating
								video: {
									video_W: "518",
									video_H: "261",
									source: assetUrl,
									flash: {
										title: title,
										imgsrc: posterImage
									}
								}
							}
	
							mediaType = $.nano(templateHTML, data); //Use nano templating engine to replace string variables
							videoURL.push(assetUrl); //Find each video asset url and place in an Array			
                    	} else
							mediaType = '<img src="' + posterImage + '"  alt="" height="261" width="518" />';
					else
                        mediaType = '<img src="' + assetUrl + '"  alt="" height="261" width="518" />';
					
                    newHTML += '<div class="nameplate-main slide">';
                    newHTML += mediaType;
                    newHTML += '<div><h3>' + title + '</h3><div class="copy">' + bodytext + '<p><a href="' + linkToUrl + '" class="lnk-main">' + linkToLabel + '</a></p></div></div></div>';

                })
                newHTML += '</div>';


                $('.nameplate-main').replaceWith(newHTML);

                if ($('video')) { //Ipad fix to reload video src
                    $.each(videoURL, function (i) {
                        $($('video')[i]).attr('src', videoURL[i]);
                    });
                }
                //$('video').attr('src', "http://jt.staging.4ddigital.co.uk/video/460x270.mp4").load(); //Load video src for ipad bug
                $('.overview-gallery').overviewGallery();
            }

        });
    }
    // /overview slides	

    $('.breadcrumbs').css({
        'visibility': 'hidden'
    });
    
	// back link
	var subnav = $('.col-two .subnav');
	if (subnav.children().length > 0)
		subnav.children(":first").addClass('first-child');
	$('<li class="back"><a href="#">&lt;' + sbBackLabel + '</a></li>').prependTo
		($('.subnav, .nameplate-nav')).find('a').click(function () {
		if (document.referrer && document.referrer.indexOf('jaguarturkey.com') > -1)									
			history.go(-1); //If we're inside jaguar then go back a page
		else {
			var pathname = window.location.pathname; //i.e /gb/en/experience/
			
			if(endsWith(pathname, '/'))
				pathname = pathname.substring(0, pathname.length - 1); //i.e. /gb/en/experience
			
			window.location.pathname  = pathname.substring(0, pathname.lastIndexOf('/')) + '/'; //i.e. /gb/en/
		}
		
		return false;
	});
     
	//unobtrusive print button; does not appear if javascript is enabled
	(function ($) { 
		var printing = $('<li class="last-child"><a href="#" class="print-btn">'+ sbPrintLabel +'</a></li>')
			.appendTo($('.top-nav'))
			.bind('click', function() {
			   window.print();
        });

    })(jQuery);
    
	//homepage revolver
    HPvideos = Array;
    loadHPImages = function (xmlUrl) {
        $.get(xmlUrl, function (xml) {

            $('ul.pix li:not(:first)').remove(); //starting by removing all slides but the first one	
            var theSlide = [],
                newHTML = '',
                $this;
            
			var templateUrl = loadTemplate(); //call template function 
			
			var templateHTML = $.ajax({ //Load external video template
                        type: "GET",
                        url: templateUrl,
                        async: false
                    }).responseText; //Output the video template markup

            $(xml).find('slide').each(function (index) {
                theSlide[index] = {
                    type: $(this).attr('type'),
                    title: $(this).find('title').text(),
                    bodytext: $(this).find('bodytext').text(),
                    assetUrl: $(this).find('assetUrl').text(),
                    linkToLabel: $(this).find('linkToLabel').text(),
                    linkToUrl: $(this).find('linkToUrl').text(),
                    logoUrl: $(this).find('logoUrl').text(),
                    stillImageUrl: $(this).find('stillImageUrl').text()
                }

            })

            var HTMLVideoSRC, firstSlideVideo;
            HTMLVideo = '';
            j = 0; //video index variable; 

			 
            for (i = 0; i < theSlide.length; i++) {
                $this = theSlide[i];
				
			    
                switch ($this.type) {
                case 'nameplateImage':
                    HTML = '<div class="titleOverlay"><img alt="" src="' + $this.logoUrl + '" /><div><h2>' + $this.title + '</h2><span>' + $this.bodytext + '</span><a href="' + $this.linkToUrl + '">' + $this.linkToLabel + '</a></div></div><img src="' + $this.assetUrl + '" alt="" width="838" height="380" />';
                    break;

                case 'nameplateVideo':
                    HTML = '<div class="titleOverlay"><img alt="" src="' + $this.logoUrl + '" /><div><h2>' + $this.title + '</h2><span>' + $this.bodytext + '</span><a href="' + $this.linkToUrl + '">' + $this.linkToLabel + '</a><a href="?view=video&amp;asset=' + (i+1) + '" class="lnk-watch-video" rel="' + j + '">' + sbWatchVideoLabel +'</a></div></div><img src="' + $this.stillImageUrl + '" alt="" width="838" height="380" />';
					j++; //increment video index
					
					var data = { //Provide video data for templating
                        video: {
                            video_W: "838",
                            video_H: "380",
                            source: $this.assetUrl,
                            flash: {
                                url: $this.assetUrl,
                                title: $this.title,
                                imgsrc: $this.stillImageUrl
                            }
                        }
                    }
                    
					HTMLVideo += '<div class="video-hldr">' + $.nano(templateHTML, data) + '</div>'; //Use nano templating engine to replace string variables
                    if (i == 0) {
                        firstSlideVideo = HTML
                    }
                    break;

                case 'image':
				
					 if ((!theSlide[i].linkToLabel) && (!theSlide[i].bodytext || !theSlide[i].title)) { //Checks for empty linkLabel and either bodyText or title are empty
			
					 	HTML = '<img src="' + $this.assetUrl + '" alt="" width="838" height="380" />';
					 
					 } else {
					
						HTML = '<div class="titleOverlay noImg"><h2>' + $this.title + '</h2><span>' + $this.bodytext + '</span><br /><br /><a href="' + $this.linkToUrl + '">' + $this.linkToLabel + '</a></div><img src="' + $this.assetUrl + '" alt="" width="838" height="380" />';
						 
					 }
					
					break;
                }

                //if the first slide have link to a video, we add the html for a video missing in non-js version 
                if ((i == 0) && firstSlideVideo) {
                    $('li.first .lnk-watch-video').attr('rel', '0');
                }
                else {
                    newHTML += '<li class="next">' + HTML + '</li>';
                }
				
            }
			
            
			$('ul.pix').append(newHTML);

            overlayFull = $('<div class="overlayFull"></div>').hide().appendTo('body').append('<div id="video-hldr"><a href="#" id="close">' + sbLofiCloseLabel +'</a></div>');
			
            $('body').addClass("with-revolver");
            $('.pix li').imagetransition();

        });

    }
    // /homepage revolver

    // market selector
    $('.countries').prev('h2').hide();

    $('.countries h3').click(function () {
        if (!($('.countries div').is(':animated'))) {
            $(this).next("div").animate({
                height: 'toggle'
            }, 600).siblings("div:visible").slideToggle(600);
            $(this).toggleClass("active");
            $(this).siblings("h3").removeClass("active");
        }
    })
    // /market selector		

    $('.carousel_ul').Carousel(382, 500);

    $('.carousel_ul').clickable();
    $('.listing').clickable();
    $('.article-list').clickable();
	
	$('a.popup').click(function (e) {
		var _FEATURES = 'loction=yes,statusbar=0,menubar=0,resizable=yes,scrollbars=yes,dependent=yes,directories=no';
		var coords = $(this).attr('coords').split(","); // Take the size from the coords attribute
		
		e.preventDefault(); // Removed this events default action
		
		function popup(url, target, popupWidth, popupHeight) {
			if (url != undefined) {	
				popupWidth = (popupWidth) ? parseInt(popupWidth, 10) : '625'; // Radix 10
				popupHeight = (popupHeight) ? parseInt(popupHeight, 10) : '685';
				target = (target) ? target : '_blank';
				
				window.open(url, target, _FEATURES + ',width=' + popupWidth + ',height=' + popupHeight);
			}
			
			return false;
		}
		
        return popup($(this).attr('href'), $(this).attr('target'), coords[0], coords[1]);
	});
	
	/*
	var hotspots = []; // hotspot cache
	
	showHotspot = function(event, ui)
	{
		var text = $(this).next('span.tooltip');
		
		if (text.attr('class') != 'tooltip')
			return false;
		
		var drawHotspot = function(hotspot) {
			if (hotspot.length > 0) {
				text.html(hotspot);
				
				if (!window.XMLHttpRequest) // IE6
					text.fadeIn('fast')
						.css('top', event.pageY)
						.css('left', $(event.target).width() + $(event.target).position().left + 10);
				else
					text.fadeIn('fast')
						.css('top', event.pageY - document.documentElement.scrollTop)
						.css('left', event.pageX + 20);
			}
		}
		
		this.getHotspot = function() {
			var hotspotId = $(this).attr('href').split(',')[1];
			
			if (hotspotId.length > 0) {
				var hotspot = hotspots[hotspotId]; // check cache
				
				if (!hotspot) {
					var url = '/rest/item/hotspot/' + hotspotId;
					
					$.ajax({
						type: "GET",
						url: url,
						dataType: "xml",
						success: function (xml) {
							var title = $(xml).find('link title');
							var teaser = $(xml).find('link teaser');
							var image = $(xml).find('link imageUrl');
							
							var container = $('<div>').addClass('hotspot-wrapper');
							
							if (title.length > 0)
								container.append($('<h4>').attr('class', 'hotspot-title').html(title.text()));
							if (teaser.length > 0)
								container.append($('<p>').addClass('hotspot-body').html(teaser.text()));
							if (image.length > 0)
								container.append($('<img>').attr({'class':'hotspot-img', 'src':image.text()}));
							
							hotspots[hotspotId] = container;
							
							drawHotspot(hotspots[hotspotId]);
						}
					});
				} else
					drawHotspot(hotspots[hotspotId]);
			}
		}
		
		this.getHotspot();
		
		return false;
	}
	
	hideHotspot = function(event, ui)
	{
		var text = $(this).next('.tooltip');
		
		if (text.attr('class') != 'tooltip')
			return false;
	
		text.fadeOut('fast');
	}
	
	$('a[href^=event:hotspot]').each(function(){
		$(this).after($('<span/>').attr('class', 'tooltip'));
	}).hover(showHotspot, hideHotspot);
	*/
	
	$('a[href^=event:hotspot]').click(function(e){
		e.preventDefault();
		return false;
	});
	
	// Flash cover method
	formOverlay = function(url, x, y)
	{
		$('div#dialog').formOverlay(url, {'overlayWidth':x, 'overlayHeight':y});
	}	
		
	$.fn.formOverlay = function(url, options) {
		var defaults = {
			overlayWidth: 858,
			overlayHeight: 660
		};
		var options = $.extend(defaults, options);
		var overlay = this;
		var container = $('<div>').attr('id','iframe-container').css
										({'height': options.overlayHeight - 60 + 'px', // Scrollbars
										'width': options.overlayWidth - 42 + 'px'});
		var iframe = $('<iframe>').attr({'src': url,
										'allowTransparency':'true',
										'frameborder':0,
										'id':'iframe-overlay',
										'style':'background-color:transparent; display:block'
										//'onload':onloadFrame
										});
		
		iframe.appendTo(container);
		overlay.html(container); // Inject the form into the overlay
		formDialog($(this), options);
	}
	
	formDialog = function(node, options)
	{
		var overlay = node;
		
		overlay.dialog({
			'width': options.overlayWidth,
			'height': options.overlayHeight,
			'modal': true,
			'draggable': false,
			'position': 'center',
			'closeText': '',
			'close': function(event, ui){
				overlay.dialog("destroy");
				overlay.empty();
				if(options.onClose)
					onClose();
			},
			'open': function(event, ui) {
				$('.ui-widget-overlay').css('opacity', '0');
				
				var dialog = $('.ui-dialog');
				var height = dialog.height();
				dialog.prepend($('<img>').attr({ // Because we can't resize a background image
					//src: (!window.XMLHttpRequest) ? 'images/interface/overlay/background-ie6.png' : 'images/interface/overlay/background.png', // Local Image Path
					src: (!window.XMLHttpRequest) ? '/lofi/images/interface/overlay/background-ie6.png' : '/lofi/images/interface/overlay/background.png',
					'width':options.overlayWidth,
					'height':height + 16, // Height plus header, footer etc
					'id':'background'
				}));
				
				$('.ui-widget-overlay').fadeTo('slow', 0.75);
			}
		});
		
		$(window).resize(function() {
			overlay.dialog("option", "position", "center");
		});
	}
	
	$('a.dialog').click(function (e) {
										  
		var coords = $(this).attr('coords').split(","); // Take the size from the coords attribute
			   
		e.preventDefault(); // Removed the event's default action
								   
		function overlay(url, overlayWidth, overlayHeight) {
			if (url != undefined) {
				overlayWidth = (overlayWidth) ? parseInt(overlayWidth, 10) : undefined; // Radix 10
				overlayHeight = (overlayHeight) ? parseInt(overlayHeight, 10) : undefined;
				
				$('div#dialog').formOverlay(url, {'overlayWidth':overlayWidth, 'overlayHeight':overlayHeight});
			}
			
			return false;
		}
		
		return overlay($(this).attr('href'), coords[0], coords[1]);
	});
	
	//dealer locator US state selector
	setStateSelector = function( isChange )
	{
		if ($('#dealerLocatorSelector').val() == 'ct') 
		{
			$('#stateSelector').show();
			$('#dlTextControlUS').hide();
		}
		else
		{
			$('#stateSelector').hide();
			
			if ( isChange )
			{
				$('#dlTextControlUS').show().attr( 'value', '' );
			}
			else
			{
				$('#dlTextControlUS').show();
			}
		}
	}
	
	setStateSelector( false );
	$('#dealerLocatorSelector').change( function() { setStateSelector( true ) } );
})

