document.observe("dom:loaded", function() {
  
  $$('a.addCommentLink').each(function(link) {
	  link.observe('click', function(event) {
		  $('ugcAddComment').style.display = 'block';
	  });
	  
  });
  $$('a.ugcHideComments').each(function(link) {
	  link.observe('click', function(event) {
		  $('ugcAddComment').style.display = 'none';
		  $('comment_body').value = '';
		  $('clientMessage').innerHTML = '';
		  $('clientMessage').style.display = 'none';
	  });
	  
  });
  
});

var UGC = {
	loginURL: "/services/site/registration/tugs-reg-login.register",
	discussionPageEnabled: true,
	cancelBtnImgTagIe6: '<img src="/hive/images/ugc/cancel_btn_login_ie6.jpg" style="width: 40px; height: 40px;" />',
	cancelBtnImgTag: '<img src="/hive/images/ugc/cancel_btn_login.png" style="width: 54px; height: 52px;" />',
	uploadFormURL: "",
	discussUrl: "", // if empty will be constructed later
	prodAff: "SET ME", // this is required
	tugsUrl: "SET ME", // this is required
	siteUrl: "SET ME", // this is required
	iframeHeight: 330,
	iframeWidth: 550,
	loggedIn: false,
	photoDomain: "",
	photoPerPage: 10,
	currentPage: "",
	totalPhotos: "",
	photoBlock: "",
	navBlock: "",
	lastPage: "",
	retryDefault: 1,
	retry: 1,
	indexSet: false,
	indexRetrieved: false,
	jsonString: "",
	requestIndexSet: 0,
	photoIndex: 0,
	photosThisPage: 0,
	currentlySelected: "",  // itemSlug
	navIndex: 0,
	navArray: new Array(),
	ugsHash: new Hash(),
	pgSlug: "",
	galleryURL: "",
	galleryRatingAdded: false,
	errorLogged: "",
	allowVote: false,
	env: "",
	photoGalleryInit: function(jsonString, contentSlug, direction) {
		if (jsonString.indexOf('Failure of url') >= 0 || jsonString == "") {
			UGC.errorLogged = true;
			currentURL = window.location.toString();
			paramsStripped = ""
			newURL = "";
			if(currentURL.indexOf("?") > 0) {
			    paramsStripped = currentURL.substr(0, currentURL.indexOf("?"));
			}
			newURL = paramsStripped+"?reload=true";
		} else {
			var json = jsonString.evalJSON();
			if(UGC.photoIndex == 0){
				UGC.totalPhotos = json.total_entries; 
				UGC.photoDomain = json.gallery_item_domain;
				UGC.photoPerPage = json.per_page;
				UGC.lastPage = (UGC.totalPhotos < UGC.photoPerPage) ? 1 : Math.ceil(UGC.totalPhotos/UGC.photoPerPage);
				UGC.currentPage = parseInt(json.current_page);
				UGC.pgSlug = contentSlug;
				UGC.photosThisPage = (UGC.currentPage == UGC.lastPage && UGC.totalPhotos%UGC.photoPerPage != 0) ? UGC.totalPhotos%UGC.photoPerPage : UGC.photoPerPage;
			
				if (direction == "back" || direction == "last") {
					UGC.currentlySelected = json.gallery_contents[UGC.photosThisPage-1].ugs_item.id;
				} else if(UGC.getIndexPhoto() == 0 && json.gallery_contents && json.gallery_contents[0]) {
					UGC.currentlySelected = json.gallery_contents[0].ugs_item.id;
				} else if(UGC.getIndexPhoto() != 0 && UGC.indexRetrieved == true && json.gallery_contents && json.gallery_contents[0] && (direction == "forward" || direction =="first")) {
					UGC.currentlySelected = json.gallery_contents[0].ugs_item.id;
				} else {
				
					if (UGC.indexRetrieved != true) {
						UGC.currentlySelected = UGC.getIndexPhoto();
					}
					UGC.indexRetrieved = true;
				}
				if ($('tugsRating')) {
					$('tugsRating').remove();
				}
				if(UGC.errorLogged != true) {
					if ($('tugsRating')==null) {
						if (UGC.allowVote == true) {
							newRatingDiv = '<div id="photoActions"><div id="tugsRating"><div id="tugsRatingBtn" onclick="ratethisphoto()">VOTE FOR THIS BABY</div></div></div>';
						} else {
							newRatingDiv = '<div id="photoActions"><div id="tugsRating"></div></div>';
						}
						$('content').insert({bottom:newRatingDiv});
					}
					UGC.buildGallery(json, UGC.photoDomain);
				}
				if ($('tugsRating')!=null) {
					UGC.moveStars();
				}
				Event.observe($('leftarrow'), 'click', UGC.showPhoto);
				Event.observe($('rightarrow'), 'click', UGC.showPhoto);
			} else {
				//**use json to create navigation array and json object hash
				//take gallery contents and sort them
				UGC.pgSlug = contentSlug;
				//store json for future use?
				UGC.jsonString = jsonString.evalJSON();
				var temp = json.gallery_contents;
				UGC.totalPhotos = temp.length - 1;
				temp.sort(function(a,b) {return ((a.ugs_item.name == b.ugs_item.name) ? 0 : ((a.ugs_item.name > b.ugs_item.name) ? 1 : -1 ));});
				//iterate over sorted returned items using for-loop
				for( i=0; i < temp.length;i++){
					//put ugs item id into array at index i
					UGC.navArray.push(temp[i].ugs_item.id);
					//if ugs item id == UGC.photoIndex, set navIndex to i
					if(temp[i].ugs_item.id == UGC.photoIndex){
						UGC.navIndex = i;
						UGC.currentlySelected = UGC.photoIndex;
					}
					//put ugs item into hash with ugs item id as key
					//place ugs item into hash using ugs item id as key
					UGC.ugsHash.set( temp[i].ugs_item.id, temp[i].ugs_item);
				}
				
				if ($('tugsRating')) {
					$('tugsRating').remove();
				}
				
				if(UGC.errorLogged != true) {
					if ($('tugsRating')==null) {
						if (UGC.allowVote == true) {
							newRatingDiv = '<div id="photoActions"><div id="tugsRating"><div id="tugsRatingBtn" onclick="ratethisphoto()">VOTE FOR THIS BABY</div></div></div>';
						} else {
							newRatingDiv = '<div id="photoActions"><div id="tugsRating"></div></div>';
						}
						//The below is for development
						newRatingDiv = '<div id="photoActions"><div id="tugsRating"><div id="tugsRatingBtn" onclick="ratethisphoto()"></div></div></div>';
						$('content').insert({bottom:newRatingDiv});
					}
					UGC.buildGallery(json, UGC.photoDomain);
				}
				/*
				if ($('tugsRating')!=null) {
					UGC.moveStars();
				}*/
				//attach event to decrement navIndex, jumping to end if 0
				//Event.observe('leftarrow', 'click', function(){UGC.moveGallery('dec')});
				jQuery('#leftarrow').live("click", function(){
					UGC.moveGallery('dec');
				});

				//$('rightarrow').observe( 'click', UGC.moveGallery('inc'));
				//Event.observe('rightarrow', 'click', function(){UGC.moveGallery('inc')});
				
				jQuery('#rightarrow').live("click", function(){
					UGC.moveGallery('inc');
				});
			}
		}
	},
	refreshPage: function() {
		window.location.reload();
	},
	
	backtogallery: function() {
		/**
		if (UGC.env == "prod") {
			window.location="/schooldazed/gallery/";
		} else {
			window.location="/schooldazed/gallery/?logo="+UGC.getmarketcode();
		}
		*/
		window.location="/schooldazed/gallery/";
	},
	
	getmarketcode: function() {
		alert("UGC.pgSlug" + UGC.pgSlug);
		tslug = UGC.pgSlug;
		tsarray = tslug.split("_");
		return tsarray[2];
	},
	
	buildGallery: function(json, domain) {
		if(UGC.photoIndex == 0){
			indexSlug = 0;
			if (UGC.currentlySelected) {
				indexSlug = UGC.currentlySelected;
			} else if(UGC.getIndexPhoto() != 0) {
				indexSlug = UGC.getIndexPhoto();
			}
			ugsGallery = "<ul><li id='leftarrow' class='nextPhoto'><img src='/images/babies/left-arrow.png' style='margin-left:auto;margin-right:0;'></li>";
			currentItem = 0;
			if (json.gallery_contents && json.gallery_contents.length > 0) {
			  for (i=0;i<UGC.photosThisPage;i++) {
				
				if (json.gallery_contents[i].ugs_item.id == indexSlug || indexSlug == 0) {
					indexSlug = -1;
					//if(indexSlug != 0) { $('pgIndex').innerHTML = UGC.photoIndex; }
					ugsGallery = ugsGallery+"<li id=\"galleryItem"+json.gallery_contents[i].ugs_item.id+"\" class=\"selected\" >";
				} else {
					ugsGallery = ugsGallery+"<li id=\"galleryItem"+json.gallery_contents[i].ugs_item.id+"\">";
				}
				iTitle = json.gallery_contents[i].ugs_item.name.replace(/##1/g,"'");
				iTitle = iTitle.replace(/##3/g,"\"");
				iTitle = iTitle.replace(/##2/g,"\\");
				iTitle = iTitle.replace(/\\u[A-Z0-9].../g, "");
				iTitle = iTitle.replace(/\\n/g,"<br />");
				iTitle = iTitle.replace(/\\r/g,"<br />");
				
				photoDate = json.gallery_contents[i].ugs_item.ugs_photo.date_taken.split("-");
				formattedDate = photoDate[1]+"/"+photoDate[2]+"/"+photoDate[0];
				if (json.gallery_contents[i].ugs_item.description == null) {
					photoDescription = "";
			    } else {
				    photoDescription = json.gallery_contents[i].ugs_item.description.replace (/###\|\|###\|\|###/g,"--tempr-eplace--");
				    photoDescription = photoDescription.replace(/##1/g,"'");
				    photoDescription = photoDescription.replace(/##3/g,"\"");
				    photoDescription = photoDescription.replace(/##2/g,"\\");
				    photoDescription = photoDescription.replace(/[\u0080-\uFFFF]+/g, "");
				    photoDescription = photoDescription.replace(/\\u[A-Z0-9].../g, "");
				    photoDescription = photoDescription.replace(/\\n/g,"<br />");
				    photoDescription = photoDescription.replace(/\\r/g,"<br />");
				    try {
				     var tmpDesc = photoDescription.split("--tempr-eplace--");
				     photoDescription = "<strong>Cute fact</strong>: " + tmpDesc[0];
				     photoDescription += "<br/><strong>Age</strong>: " + tmpDesc[tmpDesc.length-1] + " months";
				    } catch(e) {}
			   }
	
				ugsGallery = ugsGallery+"<img src=\""+json.gallery_item_domain+""+json.gallery_contents[i].ugs_item.ugs_photo.full_photo_path+"\" /><div class=\"photoData\"><span class=\"ugsItemName\"><strong>Baby Name:</strong> "+iTitle+"</span><span class=\"ugsItemDescription\"> "+photoDescription+"</span><span class=\"ugsPhotoDate\">Date Taken: "+formattedDate+"</span></div></li>";
			  }
		    }
			ugsGallery = ugsGallery+"<li id='rightarrow' class='nextPhoto'><img src='/images/babies/right-arrow.png' style='margin-left:0;margin-right:auto;'></li></ul>";
			$('ugcGallery').innerHTML = ugsGallery;
			UGC.photoBlock = $('ugcGallery').down('ul').childElements();
			if ($('ugcGallery').down('ul').down('.selected')) {
				UGC.getComments($('ugcGallery').down('ul').down('.selected').id.substr(11));
			}
		} else {
			//get the value from the UGCnavArray using UGCnavIndex
			
			key = UGC.navArray[UGC.navIndex].valueOf();
			ugsObj = UGC.ugsHash.get(key);
			var category = "";
			if(UGC.pgSlug == "tip_sd_horrendoushair"){
				category = "Horrendous Hair";
			}
			if(UGC.pgSlug == "tip_sd_standoutexpression"){
				category = "Standout Expression";
			}
			if(UGC.pgSlug == "tip_sd_fashionfelony"){
				category = "Fashion Felony";
			}
			if(UGC.pgSlug == "tip_sd_facialflair"){
				category = "Facial Flair";
			}
			if(UGC.pgSlug == "tip_sd_foureyesfail"){
				category = "Four Eyes Fail";
			}
			/**
			if ($('tugsRating')) {
				$('tugsRating').remove();
			}
			
			ugsGallery = "<ul><li id='leftarrow' class='nextPhoto'><img src='/images/babies/left-arrow.png' style='margin-left:auto;margin-right:0;'></li>";
			ugsGallery = ugsGallery+"<li id=\"galleryItem"+ugsObj.id+"\" class=\"selected\" >";

			if (ugsObj.description == null) {
				photoDescription = "";
		    } else {
			    photoDescription = ugsObj.description.replace (/###\|\|###\|\|###/g,"--tempr-eplace--");
			    photoDescription = photoDescription.replace(/##1/g,"'");
			    photoDescription = photoDescription.replace(/##3/g,"\"");
			    photoDescription = photoDescription.replace(/##2/g,"\\");
			    photoDescription = photoDescription.replace(/[\u0080-\uFFFF]+/g, "");
			    photoDescription = photoDescription.replace(/\\u[A-Z0-9].../g, "");
			    photoDescription = photoDescription.replace(/\\n/g,"<br />");
			    photoDescription = photoDescription.replace(/\\r/g,"<br />");
			    try {
			     var tmpDesc = photoDescription.split("--tempr-eplace--");
			     photoDescription = "<strong>Cute fact</strong>: " + tmpDesc[0];
			     photoDescription += "<br/><strong>Age</strong>: " + tmpDesc[tmpDesc.length-1] + " months";
			    } catch(e) {}
		   }
			
		   //ugsGallery = ugsGallery+"<img src=\""+json.gallery_item_domain+""+ugsObj.ugs_photo.full_photo_path+"\" /><div class=\"photoData\"><span class=\"ugsItemName\"><strong>Baby Name:</strong> "+iTitle+"</span><span class=\"ugsItemDescription\"> "+photoDescription+"</span><span class=\"ugsPhotoDate\">Date Taken: "+formattedDate+"</span></div></li>";
		   //ugsGallery = ugsGallery+"<li id='rightarrow' class='nextPhoto'><img src='/images/babies/right-arrow.png' style='margin-left:0;margin-right:auto;'></li></ul>";
			
		   ugsGallery = ugsGallery+"<img src=\""+json.gallery_item_domain+""+ugsObj.ugs_photo.full_photo_path+"\" />";
		   ugsGallery = ugsGallery+"<div class=\"photoData\">";
		   if(UGC.allowVote == true){
			   ugsGallery = ugsGallery+'<div id="photoActions"><div id="tugsRating"><div id="tugsRatingBtn" onclick="ratethisphoto()">VOTE FOR THIS BABY</div></div></div>';
		   }else{
			   ugsGallery = ugsGallery+'<div id="photoActions"><div id="tugsRating"></div></div>';
		   }
		   ugsGallery = ugsGallery+"<span class=\"ugsItemName\"><strong>Baby Name:</strong> "+iTitle+"</span>";
		   ugsGallery = ugsGallery+"<span class=\"ugsItemDescription\"> "+photoDescription+"</span>";
		   //ugsGallery = ugsGallery+"<span class=\"ugsPhotoDate\">Date Taken: "+formattedDate+"</span>";
		   ugsGallery = ugsGallery+"</div></li>";
		   ugsGallery = ugsGallery+"<li id='rightarrow' class='nextPhoto'><img src='/images/babies/right-arrow.png' style='margin-left:0;margin-right:auto;'></li></ul>";
		   */
		   iTitle = ugsObj.name.replace(/###\|\|###\|\|###/g," ");
		   name = iTitle.split(" ");
		   if(ugsObj.description == null){
		    maidenName = '';
		    description = '';
		    highschool = '';
		    city = '';
		    state = '';
		    year = '';
		    fact = '';
		    nickname = '';
		    facebook = '';
		   } else {
				//.replace(/##1/g,"'") is duplicated because a whole sale replace breaks the year
				_description = ugsObj.description.replace(/##3/g,"\"");
				description = _description.split("###||###||###");
				firstname = ugsObj.name;
				firstname = firstname.substr(0,1) + firstname.substr(1,firstname.length).toLowerCase();
				lastname = ugsObj.data_three.substr(0,1) + ugsObj.data_three.substr(1,ugsObj.data_three.length).toLowerCase();
				nickname = description[0];
				fact = description[1].replace(/##1/g,"'");
				highschool = description[2].replace(/##1/g,"'");
				city = description[3].replace(/##1/g,"'");
				state = description[4];
				year = description[5].substr(2);
				facebook = description[6];
		   }
		   //<div id="arrowLeft" class="galleryArrowLeft"><button onclick="UGCslider_tip_sd_horrendoushair.rebuildGallery(-1)"></button></div>
		   //ugsGallery = '<div id="leftarrow" class="permaLinkArrowLeft"><button></button></div>';
		   ugsGallery = "";
		   ugsGallery = ugsGallery +'<div class="floatLeft dropShadow galleryWide presenter">';
		   ugsGallery = ugsGallery + '<div class="floatLeft"><img height="308" width="220" src="'+json.gallery_item_domain+ugsObj.ugs_photo.full_photo_path+'" /></div>';
		   ugsGallery = ugsGallery + '<div class="floatLeft"><div class="setRight columnWide">';
		   if(nickname == ""){
		   	ugsGallery = ugsGallery + '<div class="dataItem">' + firstname + ' ' + lastname + '</div>';
		   } else {
		   	ugsGallery = ugsGallery + '<div class="dataItem">' + firstname + ' "' + nickname + '" ' + lastname + '</div>';
		   }
		   if(facebook != ''){
			   if(facebook.indexOf('http://') == -1){
				   	facebook = 'http://' + facebook;
			   }
			   ugsGallery = ugsGallery + '<div class="dataItem"><a href="' + facebook + '"><img src="/images/schooldazed/facebook.png" title="See Me Now" alt="See Me Now"/></a></button></div>';
		   }
		   		   
		   ugsGallery = ugsGallery + '<div class="dataItem">'+ highschool +'</div>';
		   ugsGallery = ugsGallery + '<div class="dataItem">'+ city + ', '+  state +'</div>';
		   ugsGallery = ugsGallery + '<div class="dataItem"><br/></div>';
		   ugsGallery = ugsGallery + '<div class="dataItem">Class of \'' + year + '</div>';
		   ugsGallery = ugsGallery + '<div class="dataItem">' + category + '<br/></div>';
		   ugsGallery = ugsGallery + '<div class="dataItem"><br/></div>';
		   if(description[1] != ""){
		   	ugsGallery = ugsGallery + '<div class="dataItem">"'+ fact +'"<br/></div>';
		   } else {
		   	ugsGallery = ugsGallery + '<div class="dataItem">'+ fact +'<br/></div>';
		   }
		   ugsGallery = ugsGallery + '<div class="dataItem"><br/></div>';
		   ugsGallery = ugsGallery + '</div></div>';
		   
		   
		   ugsGallery = ugsGallery + '</div>';
		   //<div id="arrowRight" class="galleryArrowRight"><button onclick="UGCslider_tip_sd_horrendoushair.rebuildGallery(1)"></button></div>
		   //ugsGallery = ugsGallery + '<div id="rightarrow" class="permaLinkArrowRight"><button></button></div>';
		   $('ugcGallery').innerHTML = ugsGallery;
		}
	},
	getPhotoBlock: function(page, direction) {
		// button gets disabled and spinner appears.					
		// replace arrow image with spinner here-
		
		//var rightArrowImg = $('rightarrow').down(0);
		//rightArrowImg.writeAttribute('src', '/images/babies/ajax-loader-pink.gif')
			//.setStyle({marginTop: '17px'});
			//Event.stopObserving($('rightarrow'), 'click', UGC.showPhoto);
		
		if(UGC.photoIndex == 0){	
			var rand = Math.floor(Math.random()*10000000);
			var url = "getRating.front?page="+page+"&slug="+UGC.pgSlug+"&page_size="+UGC.photoPerPage+"rand="+rand;
			//var url = "getUGC.front?page="+page+"&slug="+UGC.pgSlug+"&page_size="+UGC.photoPerPage+"rand="+rand;
			new Ajax.Request(url, {
		        method:'get',
		        onSuccess: function(transport){
		            var response = transport.responseText || "no response";
		            
		            if(response.indexOf('Failure of url') >= 0 || response.indexOf('no response') >= 0 ){
						
						if (UGC.retry > 0)
							{
								UGC.retry--;
								
								//UGC.errorMessage('Retrying');	
								setTimeout(function() { 
									UGC.showPhoto();
								}, 1000);
								 
								
							} else {
								if (UGC.allowRetryError != "no" && UGC.allowRetryError != "false"){
	
									var msg = '<div style="font-size:13px"><strong>Please be patient.</strong><br />';
									msg += 'Due to overwhelming useage, the site is running a little sluggish.<br />';
									msg += '<strong>Please try again in a few minutes.</strong><br />';
									msg += '<i>We\'re working hard to make sure the site is as user friendly as possible.</i></div>';
									UGC.errorMessage(msg);
	
								}
								//TODO: remove this, I think... not required here
								$('rightarrow')
									.down(0)
									.writeAttribute('src', '/images/babies/right-arrow.png').setStyle({
										marginTop: 0
									})
									.observe('click', UGC.showPhoto);
								UGC.retry = UGC.retryDefault;
							}
						}else{
		            
							firstPos = response.indexOf('#*#*#')+5;
							var jsonAlt1 = response.substr(firstPos);
							endPos = jsonAlt1.indexOf('#*#*#');
							var pulledJSON = jsonAlt1.substr(0, endPos);
							if(direction) {
								UGC.photoGalleryInit(pulledJSON, UGC.pgSlug, direction); 
							} else {
								UGC.photoGalleryInit(pulledJSON, UGC.pgSlug);
							}
								if (!!window.carnival ) { 		
									carnival.metrics.init();		
										new memberNav('#tugsRatingBtn', function() {}, function(){			
										$('tugsRatingBtn').onclick = function(){ 				
											carnival.utils.popUp(carnival.configuration('hostname')+carnival.configuration('userPath')+'/popupsignon.html?bcode=babies2010&callbackUrl='+carnival.utils.cleanLocation())}}).writeNav(); 				
											carnival.user.afterLogin(function(){ratethisphoto();$('tugsRatingBtn').onclick = function(){ratethisphoto() }});}	
							}
				},
		        onFailure: function() {
		            // alert("ajax request for get photos");
		        }
		    });
		} else {
			//rebuild the photo without an ajax call
			UGC.buildGallery(UGC.jsonString,UGC.photoDomain);
			if (!!window.carnival ) { 		
												carnival.metrics.init();		
													new memberNav('#tugsRatingBtn', function() {}, function(){			
													$('tugsRatingBtn').onclick = function(){ 				
														carnival.utils.popUp(carnival.configuration('hostname')+carnival.configuration('userPath')+'/popupsignon.html?bcode=babies2010&callbackUrl='+carnival.utils.cleanLocation())}}).writeNav(); 				
														carnival.user.afterLogin(function(){ratethisphoto();$('tugsRatingBtn').onclick = function(){ratethisphoto() }});}	
			
		}
	},
	showPhoto: function(e) {
	    
		UGC.getPhotoBlock(1, "last");
		$('clientMessage').innerHTML = "";
		/*$$('iframe.ad').each(function(setAd){
			setAd.src = setAd.src;
		});*/		
	},
	getComments: function(disItem) {

	},
	displayComments:function(commentJSON, currentItem) {
	
	},
	displayHover: function(ratingId, star) {
		$R(1,star).each(function(i) {
			$('star_'+ratingId+'_'+i).setAttribute('src', '/hive/images/ratings/rating_over.jpg');
		});
	},
	displayNormal: function(ratingId, star) {
		$R(1,star).each(function(i) {	
			var IDtoFind = 'star_'+ratingId+'_'+i;
			var status = $(IDtoFind).className;

			$('star_'+ratingId+'_'+i).setAttribute('src', '/hive/images/ratings/rating_'+status+'.jpg');
		});
	},
	submitRating: function(ui,un) {

		var starID = this.id;
		var voteAmt = 5;
		var ratings = $('tugsRating');
		var clientmessage = $('clientMessage');
		var itemSlug = UGC.currentlySelected;
		var params = "";
		var requestURL = "";
		if(UGC.photoIndex == 0){
			itemSlug = UGC.photoIndex;
			params = "rate[score]="+voteAmt+"&ui="+ui+"&un="+un;
			requestURL = "getRating.front?slug="+itemSlug+"&score="+voteAmt+"&parent_slug="+UGC.pgSlug;
			//requestURL = "getUGC.front?slug="+itemSlug+"&score="+voteAmt+"&parent_slug="+UGC.pgSlug;
		}else{
			itemSlug = UGC.currentlySelected;
			params = "rate[score]="+voteAmt+"&ui="+ui+"&un="+un;
			requestURL = "getRating.front?slug="+itemSlug+"&score="+voteAmt+"&parent_slug="+UGC.pgSlug;
			//requestURL = "getUGC.front?slug="+itemSlug+"&score="+voteAmt+"&parent_slug="+UGC.pgSlug;
		}
		
		var number_of_stars = 5;
		
		new Ajax.Request(requestURL, {
	        method:'post',
			parameters:params,
			onLoading: function() {
				ratings.innerHTML = "<img id='loadIMG' src='/hive/images/ratings/ajax-loader.gif' width='16' height='16' />";
			},
	        onSuccess: function(transport){
				response = transport.responseText || "no response";
				hasrate = response.indexOf('{"rate":'); 
				if (hasrate < 0){
					UGC.errorMessage('<p>Oopsie!</p><p>It looks like you have already voted for this baby today.</p><p>To make sure everyone plays nice, the rules say,<p>"One vote per person and per valid email address, per day."</p>Please come back tomorrow.');
				}
				ratings.innerHTML ="Thanks for your vote!";
				clientmessage.innerHTML="Thanks for participating in the Beautiful Babies Contest! Please remember you can only place one vote per photo per day.";
			},
			onFailure: function() {
				// alert('Problem getting rating');
			}
		}); 
	},
	moveStars: function() {
		stars = $('tugsRating');
		currphoto = $('ugcGallery').down('.selected').down('.photoData');
		currphoto.insert({top:stars});
	},
	getIndexPhoto: function() {
		photoToGrab = 0;
		indexSet = UGC.requestIndexSet;
		if(indexSet != "") {
			photoToGrab = indexSet;
		}
		return photoToGrab;
	},
	uploadForm: function(upFormURL) {
		window.scroll(0,0);
		UGC.displayPopUp();
		if (navigator.appName == "Microsoft Internet Explorer") {
			var ver = UGC.getInternetExplorerVersion();
			UGC.createIframe(upFormURL, UGC.iframeWidth, UGC.iframeHeight, "popUpContent");
		} else {
			UGC.createIframe(upFormURL, UGC.iframeWidth, UGC.iframeHeight, "popUpContent");
		}
	},
	errorMessage: function(message) {
		window.scroll(0,0);
		UGC.displayPopUp();
		popUp = document.getElementById('popUpContent');
		  if (popUp.hasChildNodes() ){
    			while (popUp.childNodes.length >= 1 ){
        			popUp.removeChild(popUp.firstChild );       
    		  } 
		}
		document.getElementById("popUpContent").style.backgroundImage="none";
		if (navigator.appName == "Microsoft Internet Explorer") {
			var ver = UGC.getInternetExplorerVersion();
		}
		var mDiv = document.createElement("div");
		mDiv.style.paddingTop="40px";
		mDiv.style.fontSize="18px";
		mDiv.style.color="#FFFFFF";
		
		mDiv.innerHTML =  message;
		document.getElementById("popUpContent").appendChild(mDiv);
		var cancelLink = document.createElement("a");
		if(UGC.getInternetExplorerVersion() > 0) {
			cancelLink.onclick = function() { 
				UGC.removeLoginPopUp();
			};
		} else {
			cancelLink.setAttribute("onclick", "UGC.removeLoginPopUp()");
		}
		cancelLink.setAttribute("id","ugsCancelBtn");
		if(UGC.getInternetExplorerVersion() < 7 && UGC.getInternetExplorerVersion() > 4) {
			cancelLink.style.top = "7px";
			cancelLink.style.right = "7px";
			cancelLink.style.width = "40px";
			cancelLink.style.height = "40px";
			cancelLink.innerHTML = UGC.cancelBtnImgTagIe6;
		} else {
			cancelLink.style.width = "54px";
			cancelLink.style.height = "52px"; 
			cancelLink.style.top = "0px";
			cancelLink.style.right = "44px";
			cancelLink.innerHTML = UGC.cancelBtnImgTag;
		}
		cancelLink.style.position = "absolute";
		document.getElementById("popUpContent").appendChild(cancelLink);
	},
	
	displayPopUp: function() {
		$('popUpContent', 'hudMask').each(function(s) {
	        s.setStyle({
	            display: 'block'
	        });
	    });

		if (navigator.appName == "Microsoft Internet Explorer") {
			var ver = UGC.getInternetExplorerVersion();

			if (ver < 7) {
		    	$('hudMask').style.height = document.body.offsetHeight;
			}
		}
	},
	removeLoginPopUp: function() {
		$('popUpContent', 'hudMask').each(function(s) {
	        s.setStyle({
	            display: 'none'
	        });
	    });
		var popUp = document.getElementById('popUpContent');
		while (popUp.childNodes.length >= 1 ){
        	popUp.removeChild(popUp.firstChild );       
    	} 
	},
	createIframe: function(iSrc, iWidth, iHeight, elemID) {
		ifrm = document.createElement("IFRAME");
		ifrm.setAttribute("src", iSrc);
		ifrm.setAttribute("id", "tugsIFrame");
		ifrm.setAttribute("frameborder", "0");
		if (navigator.appName != "Microsoft Internet Explorer")
			ifrm.setAttribute("scrolling", "no");
		ifrm.setAttribute("border", "0");
		ifrm.setAttribute("cellspacing", "0");
		ifrm.className = UGC.iframeClass;
		ifrm.style.width = iWidth+"px";
		ifrm.style.height = iHeight+"px";
		ifrm.setAttribute("allowTransparency", "true");
		document.getElementById(elemID).appendChild(ifrm);

		var cancelLink = document.createElement("a");
		if(UGC.getInternetExplorerVersion() > 0) {
			cancelLink.onclick = function() { 
				UGC.removeLoginPopUp();
			};
		} else {
			cancelLink.setAttribute("onclick", "UGC.removeLoginPopUp()");
		}
		cancelLink.setAttribute("id","ugsCancelBtn");
		if(UGC.getInternetExplorerVersion() < 7 && UGC.getInternetExplorerVersion() > 4) {
			cancelLink.style.top = "7px";
			cancelLink.style.right = "7px";
			cancelLink.style.width = "40px";
			cancelLink.style.height = "40px";
			cancelLink.innerHTML = UGC.cancelBtnImgTagIe6;
		} else {
			cancelLink.style.width = "54px";
			cancelLink.style.height = "52px"; 
			cancelLink.style.top = "0px";
			cancelLink.style.right = "44px";
			cancelLink.innerHTML = UGC.cancelBtnImgTag;
		}
		cancelLink.style.position = "absolute";
		document.getElementById(elemID).appendChild(cancelLink);

	},
	closeUploadForm: function() {
		document.getElementById('popUpContent').style.display='none'; 
		document.getElementById('hudMask').style.display='none';
		popUp = document.getElementById('popUpContent');
		if (popUp.hasChildNodes() ){
    		while (popUp.childNodes.length >= 1 ){
        		popUp.removeChild(popUp.firstChild );       
    		} 
		}

	},
	getInternetExplorerVersion: function() {
	  var rv = -1; // Return value assumes failure.
	  if (navigator.appName == 'Microsoft Internet Explorer')
	  {
	    var ua = navigator.userAgent;
	    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
	    if (re.exec(ua) != null)
	      rv = parseFloat( RegExp.$1 );
	  }
	  return rv;
	},
	searchUser: function(contentSlug, galleryURL) {
		var email = $('emailSearchText').value
		emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
		if (email.search(emailRegEx) == -1) {
			UGC.errorMessage('<p>Sorry...looks like the email address you entered doesn\'t belong to any of our Beautiful Babies.</p><p>Remember, to SEARCH for a baby you need to enter <i>the entire email address of the person who entered the baby into the contest</i>.</p><p>Please double check the email and try again.</p><p>If you have any questions, send us an email at beautifulbabies@tribune.com.</p><p>Good luck!</p>');
			return false;
		} 
		var params = "usearchEmail="+email;
		var requestURL = "getRating.front?slug="+contentSlug;
		//var requestURL = "getUGC.front?slug="+contentSlug;
		var number_of_stars = 5;
		new Ajax.Request(requestURL, {
	        method:'post',
			parameters:params,
	        onSuccess: function(transport){
				response = transport.responseText || "no response";
				firstPos = response.indexOf('#*#*#')+5;
				var jsonAlt1 = response.substr(firstPos); 
				endPos = jsonAlt1.indexOf('#*#*#');
				var pulledJSON = jsonAlt1.substr(0, endPos);
				hasitem = pulledJSON.indexOf('"gallery_item_domain":'); 
				if (hasitem < 0){
					//var message = '<p>Oops!</p>';
					//message = message + '<br><p style="text-align: left;">The email address you entered doesn\'t seem to belong to any of our Beautiful Babies.   Please double check that the address was the one used to enter the photo into the contest. </p>';
					//message = message + '<br><p style="text-align: left;">Remember, babies can be searched by the email address of the person who entered the photo into the contest.</p>';
					//message = message + '<br><p style="text-align: left;">If you have any questions, send the Beautiful Babies Support Team at beautifulbabies@tribune.com <mailto:beautifulbabies@tribune.com></p> ';
					//UGC.errorMessage(message);
					UGC.errorMessage('<p>Sorry...looks like the email address you entered doesn\'t belong to any of our Beautiful Babies.</p><p>Remember, to SEARCH for a baby you need to enter <i>the entire email address of the person who entered the baby into the contest</i>.</p><p>Please double check the email and try again.</p><p>If you have any questions, send us an email at beautifulbabies@tribune.com.</p><p>Good luck!</p>');
					return false;
				} else {
					var json = pulledJSON.evalJSON();
					var id = json.gallery_contents[0].ugs_item.id;
					var href = galleryURL + "?index="+id; 
					window.location = href;
				}
			},
			onFailure: function() {
				var message = '<p>Hmmmmm...</p>';
				message = message + '<br><p style="text-align: left;">It seems the email address you entered doesn\'t match any of the Beautiful Babies in the contest.  Please double check that the address was the one used to enter the photo into the contest. </p>';
				message = message + '<br><p style="text-align: left;">If you have any questions, send the Beautiful Babies Support Team at beautifulbabies@tribune.com <mailto:beautifulbabies@tribune.com></p>';
				UGC.errorMessage(message);
				return false;
			}
		}); 
	},
	moveGallery: function (direction){
		if(direction == 'inc'){
			if(UGC.navIndex == UGC.totalPhotos){
				UGC.navIndex = 0;
			} else {
				UGC.navIndex++;
			}
		}
		if(direction == 'dec'){
			if( UGC.navIndex == 0 ){
				UGC.navIndex = UGC.totalPhotos;
			} else {
				UGC.navIndex--;
			}
		}
		key = UGC.navArray[UGC.navIndex].valueOf();
		ugsObj = UGC.ugsHash.get(key);
		UGC.currentlySelected = ugsObj.id;
		UGC.showPhoto();
	}
};
