//--------- START CODE - jQuery noConflict code ------------
jQuery.noConflict();

var ongoing;
var current = "";
var header  = "staticheader";
var isRatingDone = false;
var __communityData = null;
var __currentCommunityId = null;
var __currentCommunityData = null;
var __imageSizeBlockDisplayedNow = false;
var __needToCloseImageSizeBlock = true;
var __commentsData = null;

jQuery(function() {
	jQuery("div.guyAwardIcon").easyTooltip({
		tooltipId: "easyTooltip",
		content: jQuery('#guyAwardTooltip').html()
	});
	jQuery("#parent").noContext();
	initialiseYoutubeFancybox();
	initialiseImageLinksFancybox();
	jQuery("#scroller").photoScroller({
		baseUrl: siteUrl + showPhotoPageRefreshURL,
		countParameterName: 'cnt',
		currentFrame: parseInt(sliderFrameNumber)
	});	
	
	var linkHolder = jQuery('#container-4');
	var links = jQuery('>ul li a', linkHolder);
	var containers = [];
	var tabAnimationSpeed = 400;
	jQuery.each(links, function(key, link) {
	    var container = jQuery(link.href.substr(link.href.indexOf('#')));
		if(!container) return;
		containers.push(container);
		container.hide();
		container.addClass('tabs-container');
		jQuery(link).click(function() {
			if(jQuery(link).hasClass('link')) return true;
			var activeContainer = '';
			jQuery.each(containers, function(key, containerInner) {
				if(container.get(0) != containerInner.get(0) && containerInner.css('display') == 'block') activeContainer = containerInner;				
			});
			if(activeContainer) activeContainer.slideUp(tabAnimationSpeed, function() {
				container.slideDown(tabAnimationSpeed);
			})
			else {
				if(container.css('display') == 'block') container.slideUp(tabAnimationSpeed);
				else container.slideDown(tabAnimationSpeed);
			}
			return false;
		});
		jQuery('.close', container).click(function(){
			container.slideUp(tabAnimationSpeed);
			return false;
		})
	});
	//--------- END CODE - jQuery noConflict code ------------
	
	//--------- START CODE - animation code ------------
	animatedcollapse.addDiv('div1', 'fade=3,speed=300,group=pets,persist=1,hide=1');
	animatedcollapse.addDiv('div2', 'fade=3,speed=300,group=pets,persist=1,hide=1');
	animatedcollapse.addDiv('div3', 'fade=3,speed=300,group=pets,persist=1,hide=1');
	animatedcollapse.addDiv('inviteCommboxId1', 'fade=3,speed=300,hide=1');
	animatedcollapse.addDiv('inviteCommboxId2', 'fade=3,speed=300,hide=1');
	
	animatedcollapse.init();
	//--------- END CODE - animation code ------------
	
	jQuery("#commentbutton").click(function() {
		postComment("commentbox");
	});
	jQuery("#commentbutton2").click(function(){
		postComment("commentbox2");
	});
	jQuery("#image-frame .showOnMouseOwer").slideUp();
	window['lasVegasInProcess'] = false;
	window['needToCloselasVegasInProcess'] = false;
	
	jQuery("#image-frame").hover(function() {
		if(window['lasVegasInProcess']) return;
		window['lasVegasInProcess'] = true;
		jQuery("#image-frame .showOnMouseOwer").slideDown('slow', function() {

			if(window['needToCloselasVegasInProcess']) {
				jQuery("#image-frame .showOnMouseOwer").slideUp('slow', function() {
					window['lasVegasInProcess'] = false;
					window['needToCloselasVegasInProcess'] = false;
				});
			} else {
				window['lasVegasInProcess'] = false;
			}
		});
	}, function() {
		if(window['lasVegasInProcess']) {
			window['needToCloselasVegasInProcess'] = true;
			return;
		}
		window['lasVegasInProcess'] = true;
		jQuery("#image-frame .showOnMouseOwer").slideUp('slow', function() {
			window['lasVegasInProcess'] = false;
		});
	});
	jQuery('.ppSettingsPopup').fancybox({
		'frameHeight': 510,
		'frameWidth': 808,
		'padding': 0,
		'showCloseButton': false
	})
});
	//function to open url in new window
function popUp(URL) {
	var title="Megashot";
	var id =0;
	var win_w, win_h;
	win_w = 720; 
	win_h = 400; 
	eval("page" + id + " = window.open(URL, '" + title + "', 'status=0,toolbar=0,menubar=0,resizable=0,dependent=0,scrollbars=yes, width=" + win_w + ", height=" + win_h + ",left=350,top=350');");
}

function openvideo(divid,vid,closeingdivid)
{
	document.getElementById(closeingdivid).innerHTML = '';
	document.getElementById(divid).innerHTML = '<div align="center"><object width="700" height="400"><param name="movie" value="http://www.youtube.com/v/'+vid+'" /><param name="wmode" value="transparent" /><embed src="http://www.youtube.com/v/'+vid+'&autoplay=1" type="application/x-shockwave-flash" wmode="transparent" width="700" height="400" /></object></div>';
}

function moveImageOverlayBlock(eid, animateParams, ease, afterAnimateHandler) {
	if (ongoing) return;
	jQuery('div.scrollable-menu-content').css('overflow', 'hidden');
	current = eid;
	ongoing = true;
	var el = jQuery('#' + eid);
	el.css('visibility', 'visible');
	el.animate(animateParams, 800, ease, function() {
		ongoing = false;
		if(afterAnimateHandler) afterAnimateHandler();						
	});
}

function moveMenuBlock(eid, topCoordinate, ease, afterAnimateHandler)
{
	moveImageOverlayBlock(eid, {'top': topCoordinate}, ease, afterAnimateHandler)		
}

function showSliderMenuContainers() {
	jQuery("#parent .overflowableBlock").css('z-index', 1);
	jQuery("#parent .overflowableBlock.left").css('height', '600px').css('width', '600px');		
} 

function hideSliderMenuContainers() {
	jQuery("#parent .overflowableBlock").css('z-index', -1);
	jQuery("#parent .overflowableBlock.left").css('height', '0px').css('width', '0px');		
}

function goDown(eid) {
	showSliderMenuContainers();
	var el = jQuery('#' + eid);
	el.parent('.overflowableBlock').css('z-index', 10);
	el.css('top', -el.height() +'px');
	moveMenuBlock(eid, 0, 'easeOutBack', function() {
		jQuery('.scrollable-menu-content').css('overflowY', 'auto').css('overflowX', 'hidden');
	})
}

function goUp(eid, afterAnimateHandler) {
	if (eid == "") return;
	
	moveMenuBlock(eid, -jQuery('#' + eid).height(), 'easeInBack', function() {
		current = "";
		hideSliderMenuContainers();
		if(afterAnimateHandler) afterAnimateHandler()
	})
}

function reviewCommunityRules(communityId) {
	if(jQuery('#comunityListItem' + communityId).hasClass('alreadyExists')) return;
	
	var url = siteUrl + getUserKarmaURL + "&communityId=" + communityId;
	jQuery('#communityRulesBlock .karma .messagebox').hide();
	jQuery('#communityRulesBlock .karma .spinner').show();
	
	jQuery.getJSON(url, function(data) {
		jQuery('#communityRulesBlock .karma .username').html(data.username);
		jQuery('#communityRulesBlock .karma .spinner').hide();
		if(!data.photosInCommunity) {
			jQuery('#communityRulesBlock .karma .excelent').show();
			return;
		}
		
		if(data.karma >= 3) {
			jQuery('#communityRulesBlock .karma .excelent').show();
		} else if (data.karma >= 1) {
			jQuery('#communityRulesBlock .karma .good').show();
		} else {
			jQuery('#communityRulesBlock .karma .bad').show();
		}
	});
	
	currentCommunityData = communityInformationHolder.getCommunityDataById(communityId);
	__currentCommunityId = communityId;
	__currentCommunityData = currentCommunityData;
	
	jQuery('#communityRulesBlock .rules').html(currentCommunityData['rule']);
	jQuery('#communityRulesBlock .community_name').html(currentCommunityData['name']);	
	
	showSubmenu(current, 'communityRulesBlock');
}

function sendToCommunity(redirectToCommunityPage) {		
	var image_id = document.getElementById('hidden_image_id').value;
 	var link = siteUrl + "checkImageInCommunity";
 	  	
  	var successHandler = function() {
  		if (!redirectToCommunityPage) {
  			goUp(current);
  			showSimpleAlert("Image was succesfuly added to the community.");
  			jQuery('#comunityListItem' + __currentCommunityId).addClass('alreadyExists');
  			return;
  		}
  		location.href = communitiesBaseUrl + __currentCommunityData['name'];
  	}
  	
  	var params = {'communityId': __currentCommunityId, 'image_id': image_id};
  	jQuery.post(link, params, function(data) {
  		onCheckSendImage2Community(data, successHandler);
  	}, "json");
}

function initializeCommunityForms() {
	if(__communityData) return;
	
	var data = communityInformationHolder.getReceivedData();
	if(!data['success']) {
		showSimpleAlert('Oops… problem during the request, please try again.');
		return;
	}

	__communityData = data['communities'];
	var communitiesList = '';
	jQuery(data['communities']).each(function(i) {
		var id = 'comunityListItem' + data['communities'][i]['id'];
		if(data['communities'][i]['alreadyExist']) {
			communitiesList += '<div class="menuitem alreadyExists" id="' + id +'">';
		} else {
			communitiesList += '<div class="menuitem" id="' + id +'">';
		}
		communitiesList += '<div class="imgHolder">';
		communitiesList += '<a href="#" onclick="reviewCommunityRules(\'' + data['communities'][i]['id'] + '\'); return false;">';
		communitiesList += '<img src="/mega/community_banner_thumb/' + data['communities'][i]['thumb'] + '"/>';
		communitiesList += '</a>';
		communitiesList += '</div><div class="nameHoleder">';
		communitiesList += '<a href="#" onclick="reviewCommunityRules(\'' + data['communities'][i]['id'] + '\'); return false;">';
		communitiesList += data['communities'][i]['name'];
		communitiesList += '</a>';
		communitiesList += '</div>';
		communitiesList += '<div class="removeFromCommunity"><a href="#" class="classicIcons remove" title="Remove from community" class="remove" onclick="removeFromCommunity(\'' + data['communities'][i]['id'] + '\'); return false;">&nbsp;&nbsp;&nbsp;</a></div>';
		communitiesList += '</div>';
	})

	if (communitiesList == '') {
		communitiesList += '<div class="menuitem">';
		communitiesList += 'There are no available communities';
		communitiesList += '</div>';
	}

	jQuery('#childmenu3 .scrollable-menu-content').html(communitiesList);

	jQuery('#communityRulesBlock .controls li.cancel a').click(function() {
		showSubmenu(current, 'childmenu3');
	});

	jQuery('#communityRulesBlock .controls li.next.redirect a').click(function() {
		sendToCommunity(true);
	});

	jQuery('#communityRulesBlock .controls li.next.stay a').click(function() {
		sendToCommunity(false);
	});
}

function showSubmenu(parent, child) {
	if(child == 'childmenu3') {
		initializeCommunityForms();			
	}
	if(child == "childsendheadertxt" || child == "childmenu7") {
		goUp(parent);
		return;
	}	
	
	goUp(parent, function() {
		goDown(child);
	});		
}

function clickHandler(e) {
	var elTarget = e.target;
	if(elTarget.nodeName.toUpperCase() == "DIV") {
		elTarget = jQuery('>a', elTarget)[0];
	}
	if(!elTarget) return;
	if(elTarget.nodeName.toUpperCase() == "A") {
		if(!elTarget.id) return;
		showSubmenu("mainmenu", "child" + elTarget.id);
	}
}

function checkIsNeedToCloseSizeSelectorBox() {
	__needToCloseImageSizeBlock = true;
	setTimeout(function() {
		if(__needToCloseImageSizeBlock) {
			hideSizeSelectorBox();
		}
	}, 2000);
}

function hideSizeSelectorBox(animationCompleteHandler) {
	var el = jQuery('#sizeSelectorBlock');
	moveImageOverlayBlock('sizeSelectorBlock', {'right': -el.width()}, 'easeInBack', function() {
		__imageSizeBlockDisplayedNow = false;
		__needToCloseImageSizeBlock = true;					
		hideSliderMenuContainers();
		current = '';
		if(animationCompleteHandler) animationCompleteHandler();
	});
}

function showSizeSelectorBox() {
	if (__imageSizeBlockDisplayedNow) return;
	var el = jQuery('#sizeSelectorBlock');
	el.css('right', -el.width());
	el.parent('.overflowableBlock').css('z-index', 10);
	showSliderMenuContainers();
	moveImageOverlayBlock('sizeSelectorBlock', {'right': 0}, 'easeOutBack', function() {
		__imageSizeBlockDisplayedNow = true;			
	});
}

jQuery(function() {
//--------- START CODE - drop box animation code ------------
	jQuery('#mainmenuBox').click(function() {
		if(current == 'sizeSelectorBlock') {
			hideSizeSelectorBox(function() {
				goDown('mainmenu')
			});
			return false;
		} else if(current == 'mainmenu') {
			goUp(current);
			return false;
		}
		if(current) {
			goUp(current, function() {
				goDown('mainmenu');
			});
		} else goDown('mainmenu');
		return false;
	});
	jQuery('#mainmenu').click(clickHandler);
if(!outsider) {
	jQuery('#rateLink').click(function() {
		if(current == 'sizeSelectorBlock') {
			hideSizeSelectorBox(function() {
				goDown('rightMenu')
			});
			return false;
		} else if(current == 'rightMenu') {
			goUp(current);
			return false;
		}
		if(current) {
			goUp(current, function() {
				goDown('rightMenu');
			});
		} else goDown('rightMenu');
		return false;
	});
	
	jQuery('#submitbutton').click(function(e) {
	    var params  = {};
		var rateFactorCount = 0;
		var totalRateFactors = document.getElementById("totalRateFactors").value;
		for(var i=1; i <= totalRateFactors; i++) {
			var rateFactor = jQuery('#rateFactor_'+i).val();
			params['rate_factor_' + i] = rateFactor;
			rateFactorCount++;
		}
		var image_id = document.getElementById("hidden_image_id").value;
		var milisec = new Date().getMilliseconds();
		var url =  siteUrl+"setAjaxRating?_dc=" + milisec;
		params['image_id'] = image_id;
		params['rate_factor_count'] = rateFactorCount;
		jQuery.post( url, params, function(data) {
		  getAjaxRating();
          isRatingDone = true;
          checkAutoCommentForRating();
		  jQuery('#rateLink').removeClass('RateImglink').addClass('RedRateImglink');
		}, "text");
		
		goUp(current);
	});
	
} else {
	jQuery('#commentbox, #commentbox2').keydown(function(){
		showSimpleAlert('<center>Sorry<br/>You need to loggin or register<br/> to make a comment</center>');
		jQuery('#commentbox, #commentbox2').blur();
		return false;
	});
}

jQuery('#changeImageSizeLink').mouseover(function() {
  __needToCloseImageSizeBlock = false;
  if(current == 'sizeSelectorBlock') return;
  if(current) {
      goUp(current, function() {
          if(!__needToCloseImageSizeBlock) showSizeSelectorBox();             
      });
      return;
  }
  showSizeSelectorBox();
});

jQuery('#changeImageSizeLink').mouseout(checkIsNeedToCloseSizeSelectorBox);
jQuery('#sizeSelectorBlock').mouseout(checkIsNeedToCloseSizeSelectorBox);
jQuery('#sizeSelectorBlock').mouseover(function() {
  __needToCloseImageSizeBlock = false;
});
});
//--------- END CODE - drop box animation code ------------

//--------- START CODE - intialize variables and functions ------------
var image_title_block 			= document.getElementById('image_title_block');
var artist_comment_block 		= document.getElementById('artist_comment_block');
var user_title_block 			= document.getElementById('user_title_block');
var inviteUserCommunitySection  = document.getElementById('inviteUserCommunitySection');

//----------- START VAR - hidden field ----------			
var hiddemEl 	= document.createElement('input');
hiddemEl.type 	= 'text';
hiddemEl.name 	= 'input_image_title';
hiddemEl.id	 	= 'input_image_title';
hiddemEl.style.display	= 'none';
hiddemEl.value 	= 0;
hiddemEl.setAttribute("class", "textBox");	
hiddemEl.setAttribute("onblur","return saveImageTitle();");
image_title_block.appendChild(hiddemEl);

//----------- END VAR - hidden field ----------	

//----------- START VAR - hidden field ----------			
var hiddemEl 	= document.createElement('input');
hiddemEl.type 	= 'text';
hiddemEl.name 	= 'input_user_title';
hiddemEl.id	 	= 'input_user_title';						
hiddemEl.style.display	= 'none';							
hiddemEl.value 	= 0;
hiddemEl.setAttribute("class","textBox userTitle");	
hiddemEl.setAttribute("onblur","return saveUserTitle();");

user_title_block.appendChild(hiddemEl);
//----------- END VAR - hidden field ----------	

//----------- START VAR - textarea field ----------
if(artist_comment_block) {
  var textareaEl 	= document.createElement('textarea');
  textareaEl.name 	= 'textarea_artist_comment';
  textareaEl.id	 	= 'textarea_artist_comment';							
  textareaEl.style.display	= 'none';							
  textareaEl.value 	= 0;
  textareaEl.setAttribute("onblur","return saveArtistComment();");
  
  artist_comment_block.appendChild(textareaEl);
  
  jQuery('#textarea_artist_comment').css({
    width: '550px',
    height:'80px',
    background:'#D1D1D1 none repeat scroll 0 0',
    border:'1px solid #6666CC',
    color:'#040404',
    fontSize:'16px',
    fontWeight:'bold',
    marginBottom:'15px',
    paddingTop:'4px',
    paddingLeft:'3px'
  });
}
//----------- END VAR - textarea field ----------	
	
jQuery(inviteUserCommunitySection).css({
  'float': 'right',
  'display':'none'
});
if(!isOwner) {
	//----------- START VAR - hidden field ----------
	var hiddemEl 	= document.createElement('input');
	hiddemEl.type 	= 'hidden';
	hiddemEl.name 	= 'hiddenCommunityId';
	hiddemEl.id	 	= 'hiddenCommunityId';
	hiddemEl.value 	= 0;
	
	if(inviteUserCommunitySection) {
		inviteUserCommunitySection.appendChild(hiddemEl);
	}
	//----------- END VAR - hidden field ----------
	
	jQuery('#inviteCommboxTrigger').click(function() {
		jQuery('#inviteCommboxId1').slideToggle();		
	});
} else {
  jQuery('#artistComment .editLink a').click(function() {
      changeArtistComment();
      jQuery('#artistComment .editLink a').html('');
  });
}

getAjaxRating();
getAllFavorites();
getExifImageData();

// init the number of comments
jQuery(function(){
	var image_id = document.getElementById('hidden_image_id').value;
	var milisec = new Date().getMilliseconds();
	var url = siteUrl+"loadAllComments?_dc=" + milisec;
	
	var params = {
		'id' : image_id,
		'only_quantity' : 'true'
	};
	jQuery.post(url, params, function(json){
		jQuery('#commentCounter').html(json.countComments + ' Comments ');
	}, 'json');
});