$(document).ready(function(){
	if(document.getElementById("artist")){
		var artist = document.getElementById("artist").value;
		var theme = document.getElementById("preview_input").value;
		log('theme is '+theme);
		var previoustheme = theme;
		if(artist==='house'){
			var format='';	
			var tGallery = tgGalleries();
			var tgHtml = tGallery[0];
			theme = tGallery[1];
			previoustheme = theme;
			format = tGallery[2];	
			document.getElementById("csThumbGallery").innerHTML = tgHtml;
			document.getElementById("preview_input").value = theme;
		}
	}
	var format='';	
	
	var dtimgurltype = 'old'; //Need this? I think for lp
//	var artist = 'house'; //For landing page customization
//	var format='jpg'; //Set format to default
	var previousformat = format;
	var currentpage = 'tg_1';
	var previouspage = currentpage;
	
	$('.thumbs').live('click', function(){
	 	theme = $(this).attr('id');
		dreamType(theme);
	});

	$('.pagination').live('click', function(){
		var prevCtrl = $(".pagination.tg_active");
		//Get previous index
		prevPageIndex = prevCtrl.index();	
		//log( 'prev Index: ' +  prevPageIndex );
		prevCtrl.removeClass("tg_active");


		//Get number of pagination controls, 0 counting
		var len = $(this).siblings().length;
		//log( 'Number of Pagination Controls: ' +  len );	

		//Set current index
		var pageIndex = $('#'+this.id).index();
		//log( 'Index: ' +  pageIndex );

		if (pageIndex==0 || pageIndex==len){//If next or prev arrow (first or last in siblings count) is clicked

			if (pageIndex==len){// If next arrow, add 1 to prev page index

				if (prevPageIndex==(len-1)){//If you on last page, set page Index to 1
					pageIndex = 1;
					//log( 'Next arrow clicked on last page!! -> Index: ' +  pageIndex );
				}else{
					pageIndex = prevPageIndex+1;
					//log( 'Next arrow clicked -> Index: ' +  pageIndex );
				}

			}else{//If last arrow, subtract 1 from current page index

				if (prevPageIndex==1){//If you are on first page, set page Index to last page
					pageIndex = (len-1);
					//log( 'prev arrow clicked on first page!! -> Index: ' +  pageIndex );
				}else{
					pageIndex = prevPageIndex-1;
				}
				//log( 'prev arrow clicked -> Index: ' +  pageIndex );
			}
		}

		// Get id of parent attribute of this control
		var parent=$(this).parent().attr('id');	
		//Then target the correct control to be updated by pageindex + 1 (need to add one cos first child is arrow)	
		$('#'+parent+' a:nth-child('+(pageIndex+1)+')').addClass("tg_active");

		// This is where you change the page view of the thumbs
		// Get previous thumbPage view by class, then get id of parent div
		var prevPageView = $('.tgPage.tgPageActive');
		var pageParent = prevPageView.parent().attr('id');

		// Add and remove classes to change view
		$('.tgPage.tgPageActive a').removeClass('thumbNotSelected'); //This removes the thumbNotSelected class
		prevPageView.removeClass("tgPageActive");
		$('#'+pageParent+' div:nth-child('+pageIndex+')').addClass("tgPageActive");
	});
});
//end of docready function

function imageError(img) {
	$("#shareDiv").hide();
	document.dreamForm.dreamImg.src = 'http://dreamtype.com/app/img/error-bsod1.png';
	$("#waitingDiv").hide();
}

function dreamType(theme){
		
	////////////////////////////////////////////////
	// TURN SHARING DIV ON, IF IT WAS OFF //////////
	////////////////////////////////////////////////
	$("#shareBtnContainerCover").hide();
	$("#shareDiv").show();
 	//----------------------------------------------

	////////////////////////////////////////////////
	// SET THEME AND PREVIOUS THEME ////////////////
	////////////////////////////////////////////////
	log('theme is '+theme);
	var previoustheme = document.dreamForm.theme.value;
	var artist = document.dreamForm.artist.value;
	var tok = document.dreamForm.tok.value;
	
	document.dreamForm.theme.value = theme;
	// add&remove selected class
	$('#'+previoustheme).removeClass("thumbSelected");
	$('#'+theme).addClass("thumbSelected");
	//----------------------------------------------

	////////////////////////////////////////////////
	// SET MESSAGE /////////////////////////////////
	////////////////////////////////////////////////
	mymessage = document.dreamForm.msg.value;
	//replace newlines for bug with IE or something
	mymessage = mymessage.replace(/\n\n\n\n/g,"\n");
	mymessage = mymessage.replace(/\n\n\n/g,"\n");
	mymessage = mymessage.replace(/\n\n/g,"\n");
	//----------------------------------------------
		
	////////////////////////////////////////////////
	// GET & SET FORMAT FROM REL ATTRIBUTTE ////////
	////////////////////////////////////////////////
	if(document.getElementById(theme).rel){
		if(document.getElementById(theme).rel=='png'){
			format='png';
		}else if(document.getElementById(theme).rel=='gif'){
			format='gif';
		}else{
			format='jpg';
		}
	}else{
		format='jpg';
	}
	//log('format is '+format+' previous format: '+previousformat);
	//--------------------------------------------


	////////////////////////////////////////////////
	// CONSTRUCT URL ////////////////////// ////////
	////////////////////////////////////////////////
	
	//document.dreamForm.dreamImg.src = "http://dev.dreamtype.com/c/"+ theme + "/a/4c9x/"+format+"?quality=90&msg="+ encodeURIComponent(mymessage);
	document.dreamForm.dreamImg.src = "http://img.dreamtype.com/i/"+ theme + "/a/"+tok+"/"+format+"?quality=90&msg=" + encodeURIComponent(mymessage);
	/*
	if(navigator.userAgent.indexOf("WebKit")!= -1){
		//document.dreamForm.dreamImg.src = "http://dev.dreamtype.com/c/"+ theme + "/a/4c9x/"+format+"?quality=90&msg="+ encodeURIComponent(mymessage);
		document.dreamForm.dreamImg.src = "http://img.dreamtype.com/i/"+ theme + "/a/4c9x/"+format+"?quality=90&msg="+ encodeURIComponent(mymessage);
		 } else {
		//document.dreamForm.dreamImg.src = "http://dev.dreamtype.com/c/"+ theme + "/a/4c9x/"+format+"?quality=90&msg=" + encodeURIComponent(mymessage);
		document.dreamForm.dreamImg.src = "http://img.dreamtype.com/i/"+ theme + "/a/4c9x/"+format+"?quality=90&msg=" + encodeURIComponent(mymessage);

	}*/
	//---------------------------------------------
	
	
	////////////////////////////////////////////////
	// IMAGE LOADING HANDLER ///////////////////////
	////////////////////////////////////////////////
	var dtimgurl = document.dreamForm.dreamImg.src;
	$("#waitingDiv").show();
	
	// Fade out if not IE
	dtFade('dreamImg', 0.5, 500);
		
	// Make image with random id			
	var rnd = Math.floor(Math.random() * 100000); 
	var id = "img" + rnd;
	var ftext = "function loadhandler(){ log('image has loaded.');}";
	var img = new Image();
	img.id = id;
	img.onload = function(){
		//Check to see if you got back the 1x1 pixel.gif image from server
		if(img.width==1){		
			log('you got error image');
			imageError(img);
			dtFade('dreamImg', 1, 500);
			//return	
		}else{
			dtFade('dreamImg', 1, 500);
			$("#waitingDiv").hide();
		}
	}
	//log('dtimgurl is '+dtimgurl);
	img.src=dtimgurl;

	previousformat = format;
	
	$('.tgPage.tgPageActive a').addClass('thumbNotSelected'); //This ads 60 percent opacity when user clicks on theme

	////////////////////////////////////////////////
	// GOOGLE ANALYTICS ////////////////////////////
	////////////////////////////////////////////////	
	 try {
		var msg = mymessage;
		var pageTracker = _gat._getTracker("UA-7148602-1");
		pageTracker._setCustomVar(
			  1,                   // This custom var is set to slot #1
			  "Message",           // The top-level name for your online content categories
			  msg,                 // Sets the value of "Message" to getParameter("msg") for this particular pv
			  3                    // Sets the scope to page-level 
			  ); 
		pageTracker._setCustomVar(
			  2,                   // This custom var is set to slot #2
			  "Theme",           // The top-level name for your online content categories
			  theme,                 // Sets the value of "Message" to getParameter("msg") for this particular pv
			  3                    // Sets the scope to page-level 
			  ); 

		pageTracker._trackPageview();
	 } catch(err) {}
 }

function tgGalleries(){
	var theme;
	var format;
	var thumbformat;
	var count=0;
	var pagecount=1;

	var html = "<div id='thumbGallery1' class='tgPage tgPageActive'><ul>";

		for(key in themelist){

			theme = key;
			format = themelist[key];
			if(count==0){
				var initTheme = theme;
				var initFormat = format;
			}
			if(format=='jpg'){
				thumbformat='gif';
			}else{
				thumbformat='png';
			}

			if(count%9===0 && count!==0){
				pagecount++;
				html += "</ul></div><div id='thumbGallery"+pagecount+"' class='tgPage'><ul>";
			}

			 html +="<li><a href='#' class='thumbs' rel='"+format+"' id='"+theme+"'><img src='./app/img/thumbs/80sq/"+theme+"-thumb.gif' class='timg'></a></li>";

				count++;
		}

	html +="</ul></div>";

	var arr = [html, initTheme, initFormat ];
	return arr;

}

var themelist={
	
	"dub_sticker":"png",
	"concert":"jpg",
	"iheartbutton_sticker":"png",
	"fireworks-stockholm":"jpg",
	"candyhearts_sticker":"png",
	"tron":"jpg",
	"hotfood_sticker":"png",
	"beachsun":"jpg",
	"chromium_sticker2":"png",
	
	//page 2
    "tattoo-shoulder":"jpg",
	"melt_sticker":"png",
	"cafe":"jpg",
	"rainbowstep_sticker":"png",
	"flag-splat":"jpg",
	"rainbow_sticker":"png",
	"action-skier":"jpg",
	"soupcan_sticker":"png",
	"candyhearts":"jpg",

	//page 3	
	"snowman":"jpg",
	"money":"jpg",
	"stickynote-cork":"jpg",
	"chromium":"jpg",
	"arabcatz":"jpg",
	"gap":"jpg",
	"arabian_nights":"jpg",
	"waterfall-350":"jpg",
	"heartsucker":"jpg",


	//page 4
	"redsparkle":"jpg",
	"melt":"jpg",
	"pen":"jpg",
	"earth":"jpg",
	"rose":"jpg",
	"panda":"jpg",
	"extrude_color":"jpg",
	"extrude_step":"jpg",
	"fireworks":"jpg",
		

	//page 5
	"man-sky":"jpg",
	"lightbulb":"jpg",
	"island":"jpg",
	"stop":"jpg",
	"napkin-kiss":"jpg",
	"gingerbread":"jpg",
	"bauble":"jpg",
	"rainbow":"jpg",
	"football":"jpg"

}
