$(document).ready(function () {
	
	// Checks current page and call specific functions
	
    switch (getUrlVarsFrom(document.location.href, true)['tabid']) {
	case undefined:
        setupSlideShow();
        break;
    case '1':
        setupSlideShow();
        break;
	case '5':
        initInventory();
        break;
	case '6':
        initObjectDetail();
        break;
	case '22':
        initGalleryViews();
        break;
	case '44':
        initArtistList();
        break;
    case '45':
        initArtistDetail();
        break;
	case '148':
        initPostList();
        break;
	 case '149':
        adjustPostImage();
        break;
    }

	initLanguageMenu();
	
	handleInputs();
	
})


// Change style of the text-input-field on focus
function handleInputs() {


    //handle text input
	function handleTextInput(index, domEle){
		
		 var target;
        if ($(domEle).children('input').length > 0) {
            target = 'input';
        } else {
            target = 'textarea'
        }

        if ($('label', domEle).length == 0) {
            $(domEle).append('<label />');
            $('label', domEle).html($('.label', domEle).html().replace(':', ''));
            $('span.label', domEle).remove();
        }
        $('label', domEle).attr('for', $(target, domEle).attr('id'));





        if ($(target, domEle).val() != '') {
            $('label', domEle).css('display', 'none');
        }
        $(target, domEle).focus(function () {
            if ($(this).val() == '') {
                $('label', domEle).animate({
                    opacity: 0.25
                }, 250);
            }
        });

        $(target, domEle).blur(function () {
            if ($(this).val() == '') {
                $('label', domEle).css('display', 'block');
                $('label', domEle).animate({
                    opacity: 1
                }, 250);

            }
        });
        $(target, domEle).keydown(function () {

            $('label', domEle).css('display', 'none');

        });

        $(target, domEle).change(function () {
            if ($(this).val() == '') {
                $('label', domEle).css('opacity', 1);

            }
        });

		
	}
	
    $('.input-box').each(function (index, domEle) {

       handleTextInput(index, domEle);

    });
	
}


function initGalleryViews() {
	
	$(".pop-big").fancybox({
				'padding'		: 20,

				'width'				: '90%',
				'height'			: '90%',
				'autoScale'			: true,
				'transitionIn'		: 'elastic',
				'transitionOut'		: 'none',
				'type'				: 'image'
			});
	
}

// Language menu
function initLanguageMenu() {

	$("div.lang-menu > a").each(function (index, domEle) {

		var currentLg = getUrlVarsFrom(window.location.href, false)['lg'],
			newLg = getUrlVarsFrom($(domEle).attr('href'), false)['lg'];
		if (currentLg != newLg) {

			if (currentLg === undefined) {
				if (getUrlVarsFrom(window.location.href, false)['tabid'] != undefined) {
					
					$(domEle).bind('click', function () {
						window.location = window.location.href + '&lg=' + newLg;
						return false;
					})
				}
			} else {
				$(domEle).bind('click', function () {
					window.location = window.location.href.replace('lg=' + currentLg, 'lg=' + newLg);
					return false;
				})
			}

		} else {
			$(domEle).bind('click', function () {
				window.location = window.location.href;
				return false;
			})

		}

	})

}

function initObjectDetail() {
	
	//fix title
	$('h1 span.title-1').html($('h1 span.title-1').html().replace('(', '<span class="secondary-text">').replace(')', '</span>'))
	$('div.image-area img').load(function(){
		$('div.navigation-area').css('margin-right', $('div.image-area').width() - $('div.image-area img').width())
	})
}

// Inventory page
function initInventory() {
	
	//$('.objects-table:eq(0)').css('margin-top',  $('h1.title-1').offset().top - $('.objects-table:eq(0) h2').offset().top + 100);
	
}

/* Search Functions */

function submitQuickSearch() {
    var keyWords = document.getElementById('inpQuickSearch').value;
    document.location.href = document.location.href.split('?')[0] + '?tabid=5&keyword=' + keyWords;
}

function submitCategory() {
    var url = document.getElementById('selCategory').value;
    document.location.href = document.location.href.substr(0, document.location.href.indexOf('DesktopDefault.aspx')) + url;
}

function entsub(e) {
    var evt = window.event ? e.keyCode : e.which;
    var keyPressed = evt;

    if (keyPressed == 13) {
        submitQuickSearch();
        return false;
    } else {
        return true;
    }
}

// Set Blog image margins
function adjustPostImage() {

    $('p.blogImageStyle img').each(function (index, domEle) {

        if ($(domEle).css('float') == 'right') $(domEle).css('margin-right', 10);
        if ($(domEle).css('float') == 'left') $(domEle).css('margin-left', 0);
    });
}


// Post list

function initPostList() {
	
	$('table.list-area tr').each(function(index,domEle){
		
		if($('div.paragraph.post-content img', domEle).length > 0) {
			
			//$('div.paragraph.post-content img:first', domEle).appendTo('div.right-area', domEle);
			$('div.right-area', domEle).append($('div.paragraph.post-content img:first', domEle));
			
			
		}
		
	})
	
}

// Artist List Page
function initArtistList() {
	
	var 
		totalHeight=0,
		totalImages = $('img.artist-image').length,
		loadedImages=0;
	
	$('table.list-area td').each(function(index,domEle){
		
		if ($('img.artist-image', domEle).length > 0 && $('img.artist-image', domEle).attr('src').indexOf('noimage') < 0) {
		
			$('img.artist-image', domEle)
			.appendTo('div.content div.right-area div.image-area')
			.addClass('artist' + index)
			.load(function(){
				
				if ($(this).height() > totalHeight) totalHeight = $(this).height();
				$('div.content div.right-area div.image-area').height(totalHeight);
				});
			
		}
		
		
		
		$('a.artist-name',domEle).hover(function () {
				
				$('img.artist' + index).fadeIn('fast');
	
			}, function () {
			   
				$('img.artist' + index).fadeOut('fast');
		


        })
	
	})
	
	
	
	
}

// Artist details page
function initArtistDetail() {

	//initInnerSlider();
	
	//fix title
	$('h1 span.title-1').html($('h1 span.title-1').html().replace('(', '<span class="secondary-text">').replace(')', '</span>'));
	
	$('a.toggle-biography').click(function(){
		
		$('div.text-area').slideToggle();
		
	})
	
	if ($('div.text-area').text().replace(/[ |\t|\n]/g,'').length == 0) $('a.toggle-biography').hide();
	//alert( $('div.text-area').text().replace(/[ |\t]/g,'').length);
}

// Artist details' page slideshow
function initInnerSlider() {

	
	var 
		// Create a variable to store the number of the total loaded images
		loadedThumbs = 0,
		// Create variable to calculate the number of screens (or series of thumbs that can be seen at once)
		totalScreens = 1,
		// Current number of the screen being showed
		currentScreen = 1;
	
	// For each object
	$('div.object').each(function(index, domEle){
		
		// Create a new slide
		$('div#slides-container').append('<div class="slide" />');
		
		// Append the object to the new slide
		$(domEle).appendTo('div#slides-container > div.slide:last');
	
		// When each image is loaded
		$('img', domEle).attr('src', $('img', domEle).attr('src').replace('cell=592,700','cell=523,245')).load(function () {	
		
			// increment loaded-image counter
			loadedThumbs++;
			
			// if all images are loaded
			if (loadedThumbs == $('div.object').length) {
				
			// Create a variable for the width of the current serie of thumbs
				var
					serieWidth = 0;
					
				// Loop through all thumbnails
				for (var i = 0; i < $('div.object').length; i++) {
	
					// Increment the serie width with the current image width
					serieWidth += $($('#slides-container > div.slide')[i]).width()
	
					// Plus the margins
					+ parseInt($($('#slides-container > div.slide')[i]).css('margin-right').replace('px', ''));
					
					// If the width is bigger than the container, go to next serie
					if (serieWidth >= 523) {
						
						
						// Increment screen (serie) counter
						totalScreens++;
	
						
						
						// To start the count of the width of the next serie, we
						// set the serie width to the size of the current thumb image
						// that is the first thumb of the next serie
						serieWidth = $($('div.object img')[i]).width()
	
						// Add its margins
						+ parseInt($($('div.object img')[i]).css('margin-right').replace('px', ''));
					}
					// Add a variable to the current thumbnail image element with the value of its serie (page) number
					$($('div.object img')[i]).data('serie', totalScreens);
					
					// Add a class to the current thumbnail image element with the value of its serie (page) number
					$($('#slides-container div.slide')[i]).addClass('serie' + totalScreens);
	
	
				}
				
				for (var i = 1; i <= totalScreens; i++) {
					
					$('#slides-container').append('<div class="screen screen' + i +'" />')
					
					
					$('#slides-container div.slide.serie' + i).appendTo('#slides-container div.screen' + i);
					
					
					
				}
				
				
				
				// set container width to total screens times container total width
				$('div#slides-container').width(totalScreens * 523);
				
				// Hide the back and forward buttons if they are not needed
				hideUnusedButtons();
	
			}
	
		})
		
		
	})
	


	// ===============
	// Setup Inner Slider Butons
	
	// Hide unused slider navigation buttons
	function hideUnusedButtons() {
	
		currentScreen == 1 ? $('div#controls a.previous').css('visibility', 'hidden') : $('div#controls a.previous').css('visibility', 'visible');
		currentScreen == totalScreens ? $('div#controls a.next').css('visibility', 'hidden') : $('div#controls a.next').css('visibility', 'visible');
		
	}
	
	
	$('div#controls a.previous').click(function () {
						
		if (currentScreen > 1) {
			$('div#slides-container').animate({
				marginLeft: "+=523"
			}, 1500);
			
			currentScreen--;
			
			hideUnusedButtons()
			
		}
		return false;
	});
	$('div#controls a.next').click(function () {
		if (currentScreen < totalScreens) {
			$('div#slides-container').animate({

				marginLeft: '-=523'

			}, 1500);
			currentScreen++;
		
			hideUnusedButtons()
		
		}
		return false;
	});
	
	
	
}

// Get variables from the url
function getUrlVarsFrom(url, preventUnwantedVars) {
    var vars = [],
        hash;
    var hashes = url.split('#')[0].slice(url.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        if (preventUnwantedVars == 1) {
            if (hash[0] != 'lg' && hash[0] != 'objectid' && hash[0] != 'tabindex' && hash[0] != 'page' && hash[0] != 'keyword' && hash[0] != 'mediaid') {
                if (hash[0] == 'categoryid' && hash[1] == 0) {} else {
                    vars.push(hash[0]);
                    vars[hash[0]] = hash[1];
                }
            }
        } else {
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
    }
    return vars;
}


//slideshow
var	intervalHandle = null;
function createHomePageImages(imageUrl, imgWidth, imgHeight, container) {

    var partPercentage = 0.1,
        partSize = 400,
        //size of the slices
        imgSize = partSize * (100 / (partPercentage * 100)),
        // set default values for the screen size, those values will be updated on document ready
        zoom = 0,
        zoomRef = 0,
        difference, scrollLeft = 0,
        scrollTop = 0;

    function applyImgSizeToContainer() {
        $(container + ' .imageContainer').css('width', imgWidth + 'px').css('height', imgHeight + 'px');
    }

    function drawImage() {

        applyImgSizeToContainer();


        if ($(container + ' .layer.zoom').length == 0) $(container + ' .imageContainer').append("<div class='layer zoom'></div>");

        //clear container
        $(container + ' .imageContainer .layer').html('');

        //loop through image slices
        for (y = 0; y <= Math.ceil(imgHeight / partSize); y += 1) {
            var top = y * partPercentage;
            for (x = 0; x <= Math.ceil(imgWidth / partSize); x += 1) {
                var left = x * partPercentage;


                //check if slice is in the viewable area, and if so, append it
                if (
					(
						(
							(x + 1) * partSize >= -scrollLeft && 
							(x + 1) * partSize <= -scrollLeft + screenWidth
						) 
						|| 
						(
							x * partSize >= -scrollLeft &&
							x * partSize <= -scrollLeft + screenWidth
						)
					) 
					&& 
					(
						(
							(y + 1) * partSize >= -scrollTop && 
							(y + 1) * partSize <= -scrollTop + screenHeight 
						)
						|| 
						(
							y * partSize >= -scrollTop && 
							y * partSize <= -scrollTop + screenHeight
						)
					)
				) 
				{
                //append image slices
                $(container + " .zoom").append("<img src='" + imageUrl + "?rgn=" + left + "," + top + "," + partPercentage + "," + partPercentage + "&wid=" + partSize + "&effect=bg,c9c9cb&qlt=68&cvt=jpeg' style='position:absolute; left:" + x * partSize + "px; top:" + y * partSize + "px' />");
				}

            }
        }






    }

    function applyZoom() {

        if (screenWidth / screenHeight < imgWidth / imgHeight) {
            difference = 0;
            //scrollLeft=((($(window).height() / imgHeight) *  imgWidth) - screenWidth)/4;
            //$(container + ' .imageContainer').css('left', -scrollLeft);
			
			scrollLeft = (screenWidth - ((screenHeight / imgHeight) * imgWidth))/2;
            $(container + ' .imageContainer').css('left', scrollLeft);
			scrollTop = 0;
            $(container + ' .imageContainer').css('top', scrollTop);
			
        } else {
			
			
             scrollLeft = 0;
            $(container + ' .imageContainer').css('left', scrollLeft);
			scrollTop = (screenHeight - (($(window).width() / imgWidth) *  imgHeight))/2;
            $(container + ' .imageContainer').css('top', scrollTop); 
			
            difference = (screenWidth - ((screenHeight / imgHeight) * imgWidth));
        }
        // real width is ($(window).height() / imgHeight) *  imgWidth
        // start with image at fullscreen
        partPercentage = 1 / ((screenHeight + (difference * (imgHeight / imgWidth))) / partSize);

        //alert(screenWidth -(screenHeight / imgHeight) *  imgWidth);
        imgSize = partSize * (100 / (partPercentage * partSize));

    }


    function init() {
        //apply zoom
        applyZoom();
        drawImage();

    }


    $('.screen').height($(window).height());
    $('.screen').width($(window).width());
    //get screen size
    screenWidth = $('.screen').width();
    screenHeight = $('.screen').height();
    init();



}


function setupSlides() {

    $('#slideshow').fadeOut(1);
    $('.contentPane').css({
        'background': 'url(media/downtown-media/image/loader.gif) 50% 50% no-repeat',
        'height': $(window).height() - 200,
        'width': '100%'
    });
	
	
	
    createHomePageImages("http://asimg.artsolution.net/tsmedia/downtowndowphoto/galerie-downtown-francois-laffanour-slide-4.jpg", 119100, 79400, '.slide1'); 
	//createHomePageImages("http://asimg.artsolution.net/tsmedia/downtowndowphoto/galerie-downtown-francois-laffanour-slide-2.jpg", 24800, 15800, '.slide2');
	
    var loaded = 0;
    var images = [];
    $('div.zoom img').each(function (index, domEle) {
        images.push($(domEle).attr('src'));



        $(domEle).load(function () {
            loaded += 1;

            if (loaded == images.length) {

$('.contentPane').css({
        'background': 'transparent'
        
    });
	
                $('#slideshow').fadeIn('slow', function () {
                    if (jQuery.browser.msie) this.style.removeAttribute("filter");
					if ($('#slideshow').length > 0 && $('#slideshow .layer.zoom').length > 1) {
						if (intervalHandle) clearInterval(intervalHandle);
						intervalHandle = setInterval("slideSwitch()", 8000);
					}

                });


            }
        });
    });

}

function setupSlideShow() {
	
	$('body').addClass('front-page-content');

    $('#slideshow').appendTo('body');





    setupSlides();
	

    function resizeSlideShow() {
        setupSlides();
    }
  


	var winWidth = $(window).width(),
	winHeight = $(window).height(),
	resizeTimeout = false;
	
	$(window).resize(function(){
	
	onResize = function() {
	//The method which sets the LEFT css property which triggers 
	//window.resize again and it was a infinite loop in Internet Explorer
	resizeSlideShow();
	}
	
	//New height and width
	var winNewWidth = $(window).width(),
	winNewHeight = $(window).height();
	
	// compare the new height and width with old one
	if(winWidth!=winNewWidth || winHeight!=winNewHeight)
	{
	if (resizeTimeout != false) window.clearTimeout(resizeTimeout);
	resizeTimeout = window.setTimeout(onResize, 1000);
	}
	//Update the width and height
	winWidth = winNewWidth;
	winHeight = winNewHeight;
	});




}


function slideSwitch() {
    var $active = $('#slideshow > div.slide.active');

    if ($active.length == 0) $active = $('#slideshow > div.slide:last');

    // use this to pull the images in the order they appear in the markup
    var $next = $active.next().length ? $active.next() : $('#slideshow > div.slide:first');

    // uncomment the 3 lines below to pull the images in random order
    // var $sibs  = $active.siblings();
    // var rndNum = Math.floor(Math.random() * $sibs.length );
    // var $next  = $( $sibs[ rndNum ] );
    $active.addClass('last-active');

    $next.css({
        opacity: 0.0
    }).addClass('active').animate({
        opacity: 1.0
    }, 2500, function () {
        if (jQuery.browser.msie) this.style.removeAttribute("filter");

        $active.removeClass('active last-active');
    });
}

