$(document).ready(function(){
	
	if ($('body').hasClass('search-results')) {
		initSearchResults();
	}
	if ($('body').hasClass('gallery-description')) {
		initGalleryDescription();
	}
	
	if ($('body').hasClass('front-page')) {
		
			
			initHome();
			
		
		
	}
	
	if ($('body').hasClass('post-list')) {
		setPostImageMargins();
	}
	
	if ($('body').hasClass('object-details')) {
		initObjectDetails();
	}
	
	if ($('body').hasClass('my-account')) {
		initMyAccount();
	}
	
	if (document.location.href.indexOf('tabid=149') > -1) {
	
		$('body').addClass('post-list').addClass('post-detail');
		setPostImageMargins();
		addPush();
	}
	
	if (document.location.href.indexOf('tabid=27') > -1) {

		initPublications();
		
	}
	

	highlightCurrentMenuItem();
	handlePlaceHolderText();
	initHeaderCollapsibleLogin();
	fixBrokenTruespectraImages();
})

//Match truespectra parameters

var dimensions = new RegExp('cell=[0-9]*,[0-9]*'),

quality = new RegExp('qlt=[0-9]*');

function randomFromTo(from, to){
	return Math.floor(Math.random() * (to - from + 1) + from);
}

function fixBrokenTruespectraImages() {
	
	
	$(window).bind('load', function() {
		$('img').each(function() {
			if((typeof this.naturalWidth != "undefined" &&
				this.naturalWidth == 0 ) 
				|| this.readyState == 'uninitialized' ) {
				$(this).attr('src', $(this).attr('src').replace(quality,'qlt=' + randomFromTo(70,100)));
			}
		}); 
	})


}

function addPush(){
	
	$('.itemWrapper').append('<div class="push"></div>');
	
}


$(window).load(function(){adjustLogo();})

// justify motto
function adjustLogo() {
	
	$('a#motto span').css('margin-right', '0px');
	var i = 0; 
	//document.title = $('a#motto span').last().offset().left + $('a#motto span').last().width() + ', ' + $('a#logo span').last().offset().left + $('a#logo span').last().width();
	while ($('a#motto span').last().offset().left + $('a#motto span').last().width() + 1 >= $('a#logo span span').last().offset().left + $('a#logo span span').last().width()) {
		
		$($('a#motto span')[i]).css('margin-right', (parseFloat($($('a#motto span')[i]).css('margin-right').replace('px', '')) - 1) + 'px');
		
		i++;
		if (i >= $('a#motto span').length) i =0;
		
	}
	
}

function initPublications() {

	$('div.publicationWrapper').each(function(index, domEle){
		
		if ((index + 1) % 3 == 0) {
		
			$(domEle).css('padding-right', 0);
			
		}
	
	})

}


// Remove placeholder text from text inputs and textareas on focus, and restore them on blur
function handlePlaceHolderText() {
    $('input[type=text]').focus(function () {
        if ($(this).val() == $(this).attr('defaultValue')) {
            $(this).val('');

        }
    });

    $('input[type=text]').blur(function () {
        if ($(this).val() == '') {
            $(this).val($(this).attr('defaultValue'));

        }
    });
	
	
	 $('textarea').focus(function () {
        if ($(this).val() == $(this).attr('defaultValue')) {
            $(this).val('');

        }
    });

    $('textarea').blur(function () {
        if ($(this).val() == '') {
            $(this).val($(this).attr('defaultValue'));

        }
    });
	
}

// Activate the collapsible functionality on the header
function initHeaderCollapsibleLogin() {
	$('ul.top-right-menu li.log-in > a').click(function(){
		
		$('ul.top-right-menu li.log-in').toggleClass('active');
		
		return false;
		
	})
}

// Homepage
var currentImage;
var currentIndex = -1;
var myTimer;
var images = [];

function showImage(index, speed) {
    currentIndex = index;


    $('div.navigation img').removeClass('active');
    $('div.navigation img').eq(index).addClass('active');

	
	$('div.slideshow > div.item').stop();
	//$('h1').html(index);
	$('div.slideshow > div.item').eq(index)
	.css({'opacity': '0', 'z-index': '9'}).fadeTo(speed, 1, function(){ 
		$('div.slideshow > div.item').css({'z-index':7});
		$('div.slideshow > div.item').eq(index).css({'z-index':8, 'filter': ''});
	});





    clearTimeout(myTimer);
    myTimer = setTimeout("showNext()", 5000);


}

function showNext() {

    var len = $('div.navigation img').length;
    var next = currentIndex < (len - 1) ? currentIndex + 1 : 0;

    showImage(next, 1500);

}


function initHome() {
	showNext(); //loads first image
        $('div.navigation img').each(function (index, domEle) {

            $(domEle).bind('click', function () {
                $('div.navigation img').removeClass('active');
                $(domEle).addClass('active');

                showImage($(domEle).index(), 1500);

            })
        })

	
	$('div.tools a.back').click(function() {
		var len = $('div.navigation img').length;
		var next = currentIndex > 0 ? currentIndex - 1 : len - 1;
		showImage(next, 300);
		return false;
	});
	$('div.tools a.next').click(function() { 
		var len = $('div.navigation img').length;
    	var next = currentIndex < (len - 1) ? currentIndex + 1 : 0;

    	showImage(next, 300);
		return false;
	});
	
	
	$('div.slideshow div.controls-area').mouseenter(function() { 
		
		$('div.slideshow div.navigation').stop().animate({
			'top':'4px',
			'width':'720px'
			
			}, 300);
		
		$('div.slideshow div.controls-area div.background').stop().animate({
			'top':'0px',
			'width':'720px'
			
			}, 300);
		
	}).mouseleave(function() {
		
		$('div.slideshow div.navigation').stop().animate({
			'top':'65px',
			'width':'0px'
			
			}, 300);
			
		$('div.slideshow div.controls-area div.background').stop().animate({
			'top':'60px',
			'width':'0px'
			
			}, 300);
		
	});
	
	$(window).load(function(){
	
		fixSlideshowCategoryListLineHeight();
	
	})
	
	function fixSlideshowCategoryListLineHeight() {
		
		line = $('div.slideshow > div.right-block > ul > li > a');
		
		line.css('margin-bottom', '10px');
		
		var i = 0, mustincrease=true; 
		while (mustincrease==true) {
			
			
			
			if ($('div.slideshow > div.right-block > ul').height() >= 320) {
				
				$(line).eq(i).css('margin-bottom', (parseFloat($(line).eq(i).css('margin-bottom').replace('px', '')) - 1) + 'px');
				
			} else {
				
				mustincrease = false;
				
			}
			
			i++;
			if (i >= $(line).length) i =0;
			
		}
		
	}

}


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;
}

// Search results page
var resultsView='grid';
function initSearchResults() {
	$('a.grid-view').click(function(){
	
		resultsView='grid';
		cblGalleryObjects.callback('grid');
	
		/*$('ul.object-list').addClass('grid-view');
		$('ul.object-list').removeClass('list-view');
		
		$('a.link-1').addClass('button-1');
		$('a.button-1').removeClass('link-1');
		
		$('div.dvListView').addClass('dvGridView');
		$('div.dvGridView').removeClass('dvListView');*/
		
		
	});
	$('a.list-view').click(function(){
	
		resultsView='list';
		cblGalleryObjects.callback('list');
		
		/*$('ul.object-list').removeClass('grid-view');
		$('ul.object-list').addClass('list-view');
		
		$('a.button-1').addClass('link-1');
		$('a.link-1').removeClass('button-1');
		
		$('div.dvGridView').addClass('dvListView');
		$('div.dvListView').removeClass('dvGridView');*/
		
	});
	
	$('a.alert-service').click(function(){
		$('div.alert-service-form').slideToggle();
		
	})
	
	
	$('select#category-select').val(getUrlVarsFrom(window.location.href)['CategoryID'])
		
	
	SearchCategoryChanged($('select#category-select'));
}

// Gallery description page
function initGalleryDescription() {

	$("a.contact-the-gallery-button").colorbox({width:"532px", inline:true, href:".lightbox.contact-the-gallery"});

	$('ul.tab-navigation a').each(function(index, domEle){
		$(domEle).click(function(){
		
			$('ul.tab-navigation li').removeClass('active');
			$(domEle).parent().addClass('active');
		
			$('div.tab-content').removeClass('active');
			$('div.tab-content-container .' + $(domEle).attr('href').slice(1)).addClass('active');
	});
		
		
		})
	
	$('a.list-view').click(function(){
		$('ul.object-list').removeClass('grid-view');
		$('ul.object-list').addClass('list-view');
		
		$('a.button-1').addClass('link-1');
		$('a.link-1').removeClass('button-1');
		
	});
	
	$('a.alert-service').click(function(){
		$('div.alert-service-form').slideToggle();
		
	})
}

$(function () {

if (document.location.href.indexOf('tabid=10') > -1) {

             var $win = $(window);

             $win.scroll(function () {
                 if ($win.scrollTop() == 0)
				 {
                     //alert('Scrolled to Page Top');
					 }
                 else if (document.getElementById('liGalleryObjects').className=="drop-shadow active" && 
						$win.height() + $win.scrollTop() >= $(document).height()-500 &&
						$win.height() + $win.scrollTop() <= $(document).height()) {
						
                     cblGalleryObjects.callback();
                 }
             });
		}
		
if (document.location.href.indexOf('tabid=4') > -1 && document.location.href.indexOf('tabid=44') <= -1) {
			
			document.getElementById('txtTypedKeyWords').value=unescape(GetURLParam('keyword'));
             var $win = $(window);

             $win.scroll(function () {
                 if ($win.scrollTop() == 0)
				 {
                     //alert('Scrolled to Page Top');
					 }
                 else if ($win.height() + $win.scrollTop() >= $(document).height()-500 &&
						$win.height() + $win.scrollTop() <= $(document).height()) {
						
                     cblGalleryObjects.callback(resultsView);
                 }
             });
		}
});


function setPostImageMargins(){
	
	function checkAndResize(domEle){
	
		if ($(domEle).height() > 590){
			$(domEle).attr('src', $(domEle).attr('src').replace(/&cell=.*?&/, '&cell=590,300&'))
			.parent().css({'margin-right': '35px', 'float' : 'left'})
			.next('.text-area').css({'float' : 'left','margin-right' : 0, 'width' : 590 - ($(domEle).width() / $(domEle).height() * 300) - 35})
		}
	}
	
	
	$('div.entry img').each(function(index, domEle) {
		
		$(domEle).attr('src', $(domEle).attr('src').replace(/&cell=.*?&/, '&cell=590,600&'))
		.load(function(){ checkAndResize(domEle); });
		
	});
	
}

function initObjectDetails() {
	
	$("a.contact-us-button").colorbox({width:"532px", inline:true, href:".lightbox.contact-us"});
	$("a.send-to-a-friend-button").colorbox({width:"532px", inline:true, href:".lightbox.send-to-a-friend"});
	
	if ($(".additional-image-table").length == 0 && $("#additional-image-container").length > 0) {
		$("#additional-image-container").remove();
	}
	
}

//MENU FUNCTIONS


function highlightCurrentMenuItem() {

    function nrKeys(a) {
        var i = 0;
        for (key in a) {
            i++;
        }
        return i;
    }

    function compareAssociativeArrays(a, b) {
        if (a == b) {
            return true;
        }
        if (nrKeys(a) != nrKeys(b)) {
            return false;
        }
        for (key in a) {
            if (a[key] != b[key]) {
                return false;
            }
        }
        return true;
    }
    //check for matches on menu
    $("ul.main-menu a").each(function (index, domEle) {
        if (compareAssociativeArrays(getUrlVarsFrom(window.location.href, 1), getUrlVarsFrom($(domEle).attr('href'), 1))) {
            $(domEle).addClass('active');
        }
    })
	
	if (getUrlVarsFrom(window.location.href, 1)['tabid'] == undefined) {
	
		$("ul.main-menu a").eq(0).addClass('active');
		
	}


}

function initMyAccount() {
	$('input.pimpInput').attr('onkeypress', '');
}



//Added By ArtSolution

function SearchBtnClicked()
{

	var keyWords = document.getElementById('txtTypedKeyWords').value;
	if(keyWords=='Search...')
    {
      keyWords="";
    }
	
	var w = document.getElementsByName('ddlCategories').item(0).selectedIndex;
	var selected_value = document.getElementsByName('ddlCategories').item(0).options[w].value;

	
	document.location.href = 'PortalDefault.aspx?tabid=4&keyword=' + keyWords + '&CategoryID='+selected_value;
}


//Added By ArtSolution

function SearchCategoryChanged(evObject) {


	var w = document.getElementsByName('ddlCategories').item(0).selectedIndex;
	var selected_text = document.getElementsByName('ddlCategories').item(0).options[w].text;
	
	document.getElementById('lblCategory').innerHTML=selected_text;
}

function ObjectCategoryChanged(evObject) {

	var w = document.getElementsByName('ddlObjectCategory').item(0).selectedIndex;
	var selected_text = document.getElementsByName('ddlObjectCategory').item(0).options[w].text;
	
	document.getElementById('lblCategory').innerHTML=selected_text;
}

function ObjectArtistChanged(evObject) {

	var w = document.getElementsByName('ddlObjectArtist').item(0).selectedIndex;
	var selected_text = document.getElementsByName('ddlObjectArtist').item(0).options[w].text;
	
	document.getElementById('lblArtist').innerHTML=selected_text;
}

function ArtistIndexCategoryChanged(event)
{
 var select_list_field = document.getElementById('ddlCategoryCat');
 var select_list_selected_index = select_list_field.selectedIndex;

 var text = select_list_field.options[select_list_selected_index].text;
 var value = select_list_field.value;

 document.getElementById("ddlCategoryLabel").innerHTML = text;

}

function SearchInDealerObjects() {
	
	var artistSelIndex = document.getElementsByName('ddlObjectArtist').item(0).selectedIndex;
	var categorySelIndex = document.getElementsByName('ddlObjectCategory').item(0).selectedIndex;
	
	var artistID = document.getElementsByName('ddlObjectArtist').item(0).options[artistSelIndex].value;
	var categoryID = document.getElementsByName('ddlObjectCategory').item(0).options[categorySelIndex].value;
	
	var keyword="-1";
	if(document.getElementById('txtObjectKeywords').value!="Search...") {
		keyword=document.getElementById('txtObjectKeywords').value;
	}
	
	cblGalleryObjects.callback(categoryID, artistID, keyword);
}

function submitQuickSearch()
 {
  var keyWords = document.getElementById('inpQuickSearch').value;
  
  if(keyWords=='Search...')
     {
      keyWords="";
     }
  
  //var val='-1';
  
  /*if(val=='-1')
  {
         if(keyWords.length<3)
         {
             document.getElementById("lblErrorMessage").style.visibility='visible';
             return;
         }
  }*/

  document.location.href = 'PortalDefault.aspx?tabid=4&keyword=' + keyWords + '&CategoryID=-1';
 }
 
 function checkEnterSearch(btn, event)
 {
 
	var w = document.getElementsByName('ddlCategories').item(0).selectedIndex;
	var val = document.getElementsByName('ddlCategories').item(0).options[w].value;
  
        if (document.all)
        {
            if (event.keyCode == 13)
            {
                var o = document.getElementById(btn).value;
                if(o=="Search...")
                {
                    o="";
                }
                
                if(val=="-1")
                {
              /*if(o.length<3)
              {
                  document.getElementById("lblErrorMessage").style.visibility='visible';
                  return;
              }*/
          }
                
                event.returnValue = false;
                event.cancel = true;
                document.location.href = 'PortalDefault.aspx?tabid=4&keyword=' + o + '&CategoryID=' + val;
            }
        }
        else if (document.getElementById)
        {
            if (event.which == 13)
            {
                var o = document.getElementById(btn).value;
    
                if(o=="Search...")
                {
                    o="";
                }
                
                if(val=="-1")
                {
              if(o.length<3)
              {
                  /*document.getElementById("lblErrorMessage").style.visibility='visible';
                  return;*/
              }
          }
                
                event.returnValue = false;
                event.cancel = true;
                document.location.href = 'PortalDefault.aspx?tabid=4&keyword=' + o + '&CategoryID=' + val;
                return false;
            }
        }
        else if (document.layers)
        {
            if(event.which == 13)
            {
                var o = document.getElementById(btn).value;
                
                if(o=="Search...")
                {
                    o="";
                }
                
                if(val=="-1")
                {
              if(o.length<3)
              {
                  /*document.getElementById("lblErrorMessage").style.visibility='visible';
                  return;*/
              }
          }
                
                event.returnValue = false;
                event.cancel = true;
                document.location.href = 'PortalDefault.aspx?tabid=4&keyword=' + o + '&CategoryID=' + val;
            }
        }
 }
 
 function checkEnter(btn, event)
 {
 
  var val="-1";
  
        if (document.all)
        {
            if (event.keyCode == 13)
            {
                var o = document.getElementById(btn).value;
                if(o=="Search...")
                {
                    o="";
                }
                
                if(val=="-1")
                {
              /*if(o.length<3)
              {
                  document.getElementById("lblErrorMessage").style.visibility='visible';
                  return;
              }*/
          }
                
                event.returnValue = false;
                event.cancel = true;
                document.location.href = 'PortalDefault.aspx?tabid=4&keyword=' + o + '&CategoryID=' + val;
            }
        }
        else if (document.getElementById)
        {
            if (event.which == 13)
            {
                var o = document.getElementById(btn).value;
    
                if(o=="Search...")
                {
                    o="";
                }
                
                if(val=="-1")
                {
              if(o.length<3)
              {
                  /*document.getElementById("lblErrorMessage").style.visibility='visible';
                  return;*/
              }
          }
                
                event.returnValue = false;
                event.cancel = true;
                document.location.href = 'PortalDefault.aspx?tabid=4&keyword=' + o + '&CategoryID=' + val;
                return false;
            }
        }
        else if (document.layers)
        {
            if(event.which == 13)
            {
                var o = document.getElementById(btn).value;
                
                if(o=="Search...")
                {
                    o="";
                }
                
                if(val=="-1")
                {
              if(o.length<3)
              {
                  /*document.getElementById("lblErrorMessage").style.visibility='visible';
                  return;*/
              }
          }
                
                event.returnValue = false;
                event.cancel = true;
                document.location.href = 'PortalDefault.aspx?tabid=4&keyword=' + o + '&CategoryID=' + val;
            }
        }
 }
 
 function submitQuickSearchCat()
 {
  var keyWords = document.getElementById('inpQuickSearchCat').value;
      
  if(keyWords=='Search')
     {
      keyWords="";
     }
  
  
  var index=document.getElementById("ddlCategoryCat").selectedIndex;
  var val=document.getElementById("ddlCategoryCat").options[index].value.toString();
  
  if(val=='-1')
  {
         if(keyWords.length<3)
         {
             //document.getElementById("lblErrorMessage").style.visibility='visible';
             //return;
         }
  }


  document.location.href = 'PortalDefault.aspx?tabid=4&keyword=' + keyWords + '&CategoryID=' + val;

 }
function checkEnterCat(btn, event)
 {
 //val = "-1";
  var index=document.getElementById("ddlCategoryCat").selectedIndex;
  var val=document.getElementById("ddlCategoryCat").options[index].value;
  
  
        if (document.all)
        {
            if (event.keyCode == 13)
            {
                var o = document.getElementById(btn).value;
                if(o=="Search...")
                {
                    o="";
                }
                
                if(val=="-1")
                {
              /*if(o.length<3)
              {
                  document.getElementById("lblErrorMessage").style.visibility='visible';
                  return;
              }*/
          }
                
                event.returnValue = false;
                event.cancel = true;
                document.location.href = 'PortalDefault.aspx?tabid=4&keyword=' + o + '&CategoryID=' + val;
            }
        }
        else if (document.getElementById)
        {
            if (event.which == 13)
            {
                var o = document.getElementById(btn).value;
    
                if(o=="Search...")
                {
                    o="";
                }
                
                if(val=="-1")
                {
              if(o.length<3)
              {
                  /*document.getElementById("lblErrorMessage").style.visibility='visible';
                  return;*/
              }
          }
                
                event.returnValue = false;
                event.cancel = true;
                document.location.href = 'PortalDefault.aspx?tabid=4&keyword=' + o + '&CategoryID=' + val;
                return false;
            }
        }
        else if (document.layers)
        {
            if(event.which == 13)
            {
                var o = document.getElementById(btn).value;
                
                if(o=="Search...")
                {
                    o="";
                }
                
                if(val=="-1")
                {
              if(o.length<3)
              {
                  /*document.getElementById("lblErrorMessage").style.visibility='visible';
                  return;*/
              }
          }
                
                event.returnValue = false;
                event.cancel = true;
                document.location.href = 'PortalDefault.aspx?tabid=4&keyword=' + o + '&CategoryID=' + val;
            }
        }
 }
 
 function GetURLParam( name )
{
	  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	  var regexS = "[\\?&]"+name+"=([^&#]*)";
	  var regex = new RegExp( regexS );
	  var results = regex.exec( window.location.href );
	  if( results == null )
		return "";
	  else
		return results[1];
}
 
 
 // Crappy code, generated by dreamweaver, copied from the old site. used on the my account page (replace me)
 
 		function MM_preloadImages() { //v3.0
		var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
			var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
			if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
		}

		function MM_swapImgRestore() { //v3.0
		var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
		}

		function MM_swapImage() { //v3.0
		var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
		if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
		}

		function MM_reloadPage(init) {  //reloads the window if Nav4 resized
		if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
			document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
		else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
		}
		MM_reloadPage(true);

		function MM_showHideLayers() { //v3.0
		var i,p,v,obj,args=MM_showHideLayers.arguments;
		for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
			if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v='hide')?'hidden':v; }
			obj.visibility=v; }
		}

		function MM_findObj(n, d) { //v4.01
		var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
			d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
		if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
		for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
		if(!x && d.getElementById) x=d.getElementById(n); return x;
		}

		function MM_openBrWindow(theURL,winName,features) { //v2.0
		window.open(theURL,winName,features);
		}
		
		function MM_jumpMenu(targ,selObj,restore){ //v3.0
  		eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  		if (restore) selObj.selectedIndex=0;
	    }

