/**
 * Gallery interface functions
 *
 * [2007-10-01 mb] created
 *
 * $Rev: 2010 $ Revision of last commit
 * $Author: martin $ Author of last commit
 * $Date: 2009-11-25 17:46:12 +0100 (Mi, 25 Nov 2009) $ Date of last commit
 */

// gallery-list
var galleries = [];

// gallery data
var galleryData = {};

// additonal plugins
var pluginConfig = {
	lightbox: {},
	stars: {},
	dialog: {}
}; 

var dialog = new Dialog(); 

/**
 * gallery reload function
 */
function loadGallery (gallery, param, callback) {

	if (typeof gallery != "object")
		return false;

  $.ajax({ type: "POST", url: (shop == false ? path.rel2root : path.rel2root_cps) + "_inc/json/concert_images.php" + pluginConfig.add_sid,
           data: {
           		dataString: JSON.stringify($.extend({ mode: "gallery"} , param)), shop: pluginConfig.shop_id
           },
           dataType: "json",
           success: function(data) {
    if (data) {

			$('#favorite-no-fav').css('display', 'none');    // hide favorite message if displayed
			galleryData.pages_total = data.pages;
			galleryData.page = data.page;
			galleryData.images_per_page = data.images.per_page;
			galleryData.total_count = data.images.total_count;

			$('.ad-thumb-list').html(data.images.content);
			$('.ad-paging').html(data.paging);

			if (data.filters) {
				$('#ad-artist-filter-list').html(data.filters.artist.list);
				if (data.filters.artist.selected) {
					$("#ad-artist-filter-selected").text(data.filters.artist.selected).show();
					$("#ad-artist-filter-not-selected").hide();
				}
				else {
					$("#ad-artist-filter-selected").hide();
					$("#ad-artist-filter-not-selected").show();
				}

				if (data.filters.concert.selected) {
					$("#ad-concert-filter-selected").text(data.filters.concert.selected).show();
					$("#ad-concert-filter-not-selected").hide();
				}
				else {
					$("#ad-concert-filter-selected").hide();
					$("#ad-concert-filter-not-selected").show();
				}

				$('#ad-concert-filter-list').html(data.filters.concert.list);
			}
		  if (data.fav_only) { // if user filter was selected and user has only favorites
		 	  $('.ad-categories li').addClass("ad-selected");
		  }

			/* important for lightbox to set the callback right here,
		 becuase the lightbox set the gallery-curennt-image index itself!	*/
			if (typeof(callback) == 'function') { // the callback has to set the galleryIndex itself, see lightbox setGalleryIndex()
	  	  callback.call(document);
	    } else {
		  	// setup gallery
					galleryData.image_id ? // find index of a image per imageID
	        gallery.current_index = parseInt(/^image([\d]*)$/.exec($(".ad-thumb-list a#" + galleryData.image_id + " .image div").attr("class"))[1]) - 1 : gallery.current_index = 0;
					gallery.findImages();
					gallery.showImage(gallery.current_index);
				//gallery_siteload = true;
			}
	  } else if (galleryData.join) { // favorites unavailable
	    gallery.current_index = 0;
			gallery.findImages();
      gallery.showImage(gallery.current_index);
			$('#favorite-no-fav').fadeIn("slow");
		} else {
			$('#gallery-left-box, #gallery-right-box').css("display", "none");
			$('#gallery-no-images').css("display", "inline-block");
		}
		$('#container').css("visibility", "visible");
		if (shop == true) {
			resize_layout();
		}
  },
  error: function(data) {
		//alert(data.responseText);
  }
	});

}

/**
 * rating build up
 */
function getRating(rating_count) {
	var rating = '<div class="ad-rating">' +
                 '<span id="stars-cap"></span>' +
                 '<div class="stars-wrapper" style="width: 90px; display: inline-block;">' +
                   '<input type="radio" name="newrate" value="1" title="" />' +
                   '<input type="radio" name="newrate" value="2" title="" />' +
                   '<input type="radio" name="newrate" value="3" title="" />' +
                   '<input type="radio" name="newrate" value="4" title="" />' +
                   '<input type="radio" name="newrate" value="5" title="" />' +
                 '</div>' +
                 '<div style="width: 90px; font-size: 10px; padding-left: 2px;">(<span class="stars-rating-count">'+rating_count+'</span> '+ (pluginConfig.lang =="de" ? 'Ratings' : 'rating') + ')</div>' +
               '</div><div class="ad-rating-message"></div>';

	return rating;
}

/**
 * sets the primary rating
 */
function setRating(rating) {
	$(".stars-wrapper").stars("select", rating);
}

/**
 * checks if image is already a favorite, if so, set a text that informs the user, otherwise bind a mousevent
 * @param {Object} check
 */
function addToFavorites(check, remove) {
	$.ajax({ type: "POST", url: (shop == false ? path.rel2root : path.rel2root_cps) + "_inc/json/concert_images.php" + pluginConfig.add_sid,
     data: {
        dataString: JSON.stringify({
			  	mode: "favorites",
					check: check,
					remove: remove,
			  	image_id: galleryData.image_id
			  }), shop: pluginConfig.shop_id
     },
     dataType: "json",
     success: function(data) {
			if (data.checked) {
			 bindRemoveFavorite();
			} else {
			 bindAddFavorite();
			}
     },
     error: function(data) {
//     	alert(data.responseText);
     }
	});
}

function bindRemoveFavorite() {
				var title = pluginConfig.lang == 'de' ? 'Dieses Bild gehört zur Liste Deiner Favoriten. Die Liste findest Du in Deinem myLive.' :
				                                        'This picture is one of your favorites. You can view and edit your favorites within your myLive.';
  var text = pluginConfig.lang == 'de' ? 'Aus Favoritenliste löschen' : 'Delete from my favorites list';
				$('.ad-gallery-favorite-button').attr('title', title);
				$('.ad-gallery-favorite-button .button-content div').text(text); // One of my favorites
				$('.ad-gallery-favorite-button .clearfix').removeClass('button btn-orange-small ad-image-report-button');
        $('.ad-gallery-favorite-button .clearfix').addClass('button btn-grey-small ad-image-report-button');
  $('.ad-gallery-favorite-button').unbind().click(function() {
     addToFavorites(false, true);
		 delete galleryData.image_id;
     loadGallery(galleries[0], galleryData);
  });
}
function bindAddFavorite() {
				var title = pluginConfig.lang == 'de' ? 'Hier klicken um dieses Bild zur Liste Deiner Favoriten hinzuzufügen. Die Liste findest Du in Deinem myLive.' :
                                                'Click here to add this picture to your favorites. You can view and edit your favorites within your myLive.';
				var text = pluginConfig.lang == 'de' ? 'Zu Favoriten hinzufügen' : 'Add to my favorites';
				$('.ad-gallery-favorite-button').attr('title', title);
				$('.ad-gallery-favorite-button').removeClass('button btn-grey-small ad-image-report-button');
				$('.ad-gallery-favorite-button').addClass('button btn-orange-small ad-image-report-button');
				$('.ad-gallery-favorite-button .button-content div').text(text);
      $('.ad-gallery-favorite-button').unbind().click(function() {
					if (pluginConfig.logged_in == 'y') {
			    addToFavorites(false, false);
			//            $('.ad-gallery-favorite-button').unbind('click');
					} else {
						dialog.setLang(pluginConfig.lang);
						dialog.loginDialog(getRedirectLink());
					}
        });
}

function getRedirectLink() {
   if (pluginConfig.shop_id == 12008)
     var link = path.web_root + pluginConfig.lang + '/login.html' + pluginConfig.insert_sid + 'action=concert_images';
   else
	   var link = path.web_root + pluginConfig.lang + '/shop/' + pluginConfig.shop_id + '/login.html' + pluginConfig.insert_sid + 'action=concert_images';

	 if (galleryData.image_id) {
	   link += '&concert_image_id=' + galleryData.image_id;
	 }
	 if (galleryData.filter.artist) {
	   link += '&filter_artist=' + galleryData.filter.artist;
	 }
	 if (galleryData.filter.concert) {
	   link += '&filter_concert=' + galleryData.filter.concert;
	 }
	 if (galleryData.order) {
	   link += '&order=' + galleryData.order;
	 }
	 if (galleryData.page) {
	   link += '&page=' + galleryData.page;
	 }

 return link;
}
/**
 * check if image has already been anounced, if not bind an event
 */
function putImageOnBlackList(check) {
	 $.ajax({ type: "POST", url: (shop == false ? path.rel2root : path.rel2root_cps) + "_inc/json/concert_images.php" + pluginConfig.add_sid,
     data: {
        dataString: JSON.stringify({
          mode: "blacklist",
          check: check,
          image_id: galleryData.image_id
        }), shop: pluginConfig.shop_id
     },
     dataType: "json",
     success: function(data) {

      if (data.checked) {
				var title = pluginConfig.lang == 'de' ? 'Du hast dieses Bild als unangemessen gemeldet. Unsere Redaktion wird Deinen Antrag prüfen und das Bild ggf. entfernen.' :
				                                        'You have marked this picture as inappropriate. Our editorial department will check your claim and will then delete this picture if need be.';

				$('.ad-gallery-blacklist-button').attr('title', title);
				var text = pluginConfig.lang == 'de' ? 'Bild gemeldet' : 'Picture reported';
        $('.ad-gallery-blacklist-button .button-content div').text(text);
        $('.ad-gallery-blacklist-button .clearfix').removeClass('button btn-white-grey-border-small ad-image-report-button');
        $('.ad-gallery-blacklist-button .clearfix').addClass('button btn-grey-small ad-image-report-button');
        $('.ad-gallery-blacklist-button').unbind('click');
      } else {
				var title = pluginConfig.lang == 'de' ? 'Wenn Du der Meinung bist, dieses Bild sei unangemessen, kannst Du uns hier durch einen Klick davon in Kenntnis setzen. Unsere Redaktion wird Deinen Antrag prüfen und das Bild ggf. entfernen.' :
                                                'If you consider this picture to be inappropriate, click this button to inform us about it. Our editorial department will check your claim and will then delete this picture if need be.';
				$('.ad-gallery-blacklist-button').attr('title', title);
				$('.ad-gallery-blacklist-button .clearfix').removeClass('button btn-grey-small ad-image-report-button');
				$('.ad-gallery-blacklist-button .clearfix').addClass('button btn-white-grey-border-small ad-image-report-button');
				var text = pluginConfig.lang == 'de' ? 'Bild melden' : 'Report picture';
        $('.ad-gallery-blacklist-button .button-content div').text(text);
        $('.ad-gallery-blacklist-button').click(function(){
          putImageOnBlackList(false);
					$('.ad-gallery-blacklist-button').unbind('click');
        });
      }
     },
     error: function(data) {
//      alert(data.responseText);
     }
  });
}

/**
 * deletes a picture
 */
function deleteImage(check) {

  	$.ajax({
  		type: "POST",
  		url: (shop == false ? path.rel2root : path.rel2root_cps) + "_inc/json/concert_images.php" + pluginConfig.add_sid,
  		data: {
  			dataString: JSON.stringify({
  				mode: "delete",
  				check: check,
          image_id: galleryData.image_id
  			}), shop: pluginConfig.shop_id
  		},
  		dataType: "json",
  		success: function(data){

  			if (data.valid) {
  				$('#gallery-delete').css('display', 'inline');
  				$('.ad-gallery-delete-button').unbind().click(function() {

//						var text = pluginConfig.lang == 'de' ? "Willst Du dieses Bild wirklich löschen?\n" +
//                "ACHTUNG: Du kannst das Löschen eines Bildes nicht wieder rückgängig machen" :
//								"Do you really want to delete this picture?\n" +
//								"ATTENTION: If you delete your picture it'll be for good";
//
//						var check = confirm(text);
//						if (check) {
//							deleteImage(false);
//							$('#gallery-delete').unbind('click');
//						}

              $('.gallery-delete-confirm').fadeIn("slow", function() {
								$('.ad-gallery-confirm-button').click(function() {

                 deleteImage(false);
                 $('.ad-gallery-confirm-button, .ad-gallery-cancel-button').unbind('click');
                 $('.gallery-delete-confirm').css('display', 'none');
	              });
	              $('.ad-gallery-cancel-button').click(function() {

	                $('.ad-gallery-confirm-button, .ad-gallery-cancel-button').unbind('click');
	                $('.gallery-delete-confirm').css('display', 'none');
	              });

							});
  				});
  			} else {
  					$('#gallery-delete').css('display', 'none');
				}
				if (data.result) {
					delete galleryData.image_id;
					loadGallery(galleries[0], galleryData);
			  }
			},
				error: function(data){
//					alert(data.responseText);
				}
		});

}

/**
 *  gets preview comments for the gallery
 */
var comments = (function() {

	var
		text = "",
		page = 1,
		action,
		get;

	function getComments(callback) {

	  $.ajax({ type: "POST", url: (shop == false ? path.rel2root : path.rel2root_cps) + "_inc/json/concert_images.php" + pluginConfig.add_sid,
	           data: {
	           		dataString: JSON.stringify($.extend({
	           			mode: "image_comments",
	           			action: action,
	           			get: get,
	           			text: text,
	           			image_id: galleryData.image_id
	           		}, galleryData, {page: page})), shop: pluginConfig.shop_id
	           },
	           dataType: "json",
	           success: function(data) {

	           	if (get == "preview")
						 	 $(".ad-comments-container").html(data.comments);

						 	if (get == "all") {

								$(".ad-comments-full").html(data.comments);
								$(".ad-comments-full-paging").html(data.paging);

								$("#ad-comments-full-current-page").html(data.current_page);
								$("#ad-comments-full-page-count").html(data.page_count);
						 	}

						 	if (action == "insert") {

						 		action = null;
		         		if (data.logged_in == "n") {

		         			dialog.loginDialog(data.redirect);
		         			return false;
		         		}
						 	}

						 	if(typeof callback == "function")
						 		callback.call(document);

	           },
	           error: function(data) {
	           	alert(data.responseText);
	           }
	  });
	}

	return {

		get: function(_get, callback) {

			get = _get;
			getComments(callback);
		},
		add: function(_text) {

			var self = this;

			text = _text;
			action = "insert";

			this.get("all", function() {
				self.get("preview")
			});
		},
		setPage: function(_page) {

			page = _page;
			this.get("all");
		}
	}
})();

/**
 * sends an image link to a user
 */
function sendImageToFriends(user_mail_to, user_message, alternative_text) {

	var default_text = false;
	if (user_message.val() == alternative_text)
		default_text = true;

	user_mail_to.removeClass("ad-form-value-incorrect");
	user_message.removeClass("ad-form-value-incorrect");

	// email check
	if (!user_mail_to.val().match(/^(([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+\,?\s*)*$/)) {
		user_mail_to.addClass("ad-form-value-incorrect");
	}

	if (!user_message.val().length) {
		user_message.addClass("ad-form-value-incorrect");
	}

	if (!user_mail_to.hasClass("ad-form-value-incorrect") && !user_message.hasClass("ad-form-value-incorrect")) {

	  $.ajax({ type: "POST", url: (shop == false ? path.rel2root : path.rel2root_cps) + "_inc/json/concert_images.php" + pluginConfig.add_sid,
	           data: {
	           		dataString: JSON.stringify($.extend({
	           			mode: "send_image_to_friends",
	           			user_mail_to: user_mail_to.val(),
	           			user_message: user_message.val(),
	           			default_text: default_text
	           		}, galleryData)), shop: pluginConfig.shop_id
	           },
	           dataType: "json",
	           success: function(data) {

	           	if (data.redirect)
	           		dialog.loginDialog(data.redirect)
	           	else {

		            // successful animation
		            $(".ad-send-to-friends-form-box").fadeOut(1000, function() {

		            	$(".ad-send-to-friends-form").hide();
		            	$(".ad-send-to-friends-successfull").show();

		            	$(this).fadeIn(1000).fadeOut(2000, function() {

		            		// restore defaults
			            	$(".ad-send-to-friends-form").show()
			            	$(".ad-send-to-friends-successfull").hide();
		            	});
		            });
	           	}
	          },
	          error: function(data) {
//	          	alert(data.responseText);
	          }
	  });
	}
}

/**
 * init third party plugins used for the gallery
 */
function initPlugins() {

  // binds the favorite-method to the favorite-button if image isnt a favorite yet
  addToFavorites(true, false);
  // binds the blacklist-method to the "announce"-button if image hasnt been announced yet
  putImageOnBlackList(true);
	// binds the delete-method to the delete-button if image is an image of user
  deleteImage(true);

	var request = null;

	/* lightbox plugin */
	$('.ad-image').lightBox(pluginConfig.lightbox);

	/* rating ui.stars plugin */
	pluginConfig.stars.cancelShow = false;
	pluginConfig.stars.disabled = false;
	pluginConfig.stars.callback = function(ui, type, value) {

		// go for rating
		request = $.ajax({ type: "POST", url: (shop == false ? path.rel2root : path.rel2root_cps) + "_inc/json/concert_images.php" + pluginConfig.add_sid,
		         data: {
		         		dataString: JSON.stringify($.extend({ mode: "rating", ratingValue: value}, galleryData)), shop: pluginConfig.shop_id
		         },
		         dataType: "json",
		         success: function(data) {

		         		if (data.logged_in == "n") {

		         			dialog.loginDialog(data.redirect);

		         		} else {

									$(".ad-rating-message").stop();
									$(".ad-rating-message").html(data.message).hide().fadeIn(1000).fadeOut(8000);
		         		}

		         	  // set rating main window
								ui.select(data.rating);
								$(".stars-rating-count").html(data.rating_count);

								// set rating in thumblist
								$("#image-rating-stars-" + data.image_id).stars("select", data.rating);
								$("#stars-rating-count-" + data.image_id).html(data.rating_count);
		         },
		         error : function(data) {

//		         	alert(data.responseText);
		         }
					});
	}

	// main ratings stars
	$(".stars-wrapper").stars(pluginConfig.stars);


}
