function Actions() {

	// helper to check if an action has been clicked or reached through
	// browser's buttons
	this.cache = {};
	// index for the array that caches the searches parameters
	this.search_id = 0;
	// array that caches the searches parameters
	this.cache_posts_search = {};

	this.post = {
		search : ''
	};

	this.topConf = {
		type1 : 'track',
		type2 : 'genre',
		topGenre : ''
	};

	this.click = function(id) {
		var sel = id;
		if (sel)
			sel += " a";
		else
			sel = "a";
		jQuery(sel).click(function(event) {
			var url = this.href;
			if (url.indexOf(baseUrl + "#") == -1) {
				// stop other click action
				event.stopImmediatePropagation();
				// preload and load breadcrumb
				return actions.jload(url, true);
			}
		});
	};

	this.jload = function(url, push) {
		var stop = actions.preload(url);
		actions.breadcrumbReload(url);
		// load the content url and change the history url
		actions.loading(url, ".tabCentral", null, function() {
			if (push)
				history.pushState(url, null, url);
			actions.loaded(url);
		});
		return stop;
	};

	this.preload = function(url) {
		var params = url.split("/");
		switch (params[4]) {
		case "genre":
			if (params.length == 7) {
				actions.supergenrePreLoad(url);
			}
			break;
		default:
			switch (params[3]) {
			case "logout":
				return true;
				break;
			}
		}
		return false;
	};

	this.loading = function(url, where, params, callback) {
		/* Load default variables if undefined */
		if (where === undefined) {
			where = ".tabCentral";
		}

		/* Ajax load of data */
		jQuery(where).load(url, params,
				function(responseText, textStatus, XMLHttpRequest) {
					if (callback !== undefined) {
						callback(responseText, textStatus, XMLHttpRequest);
					}
					actions.click(where);
				});
	};

	this.loaded = function(url) {
		var params = url.split("/");
		switch (params[4]) {
		case "chart":
		case "release":
			actions.releaseLoaded(params[params.length - 1]);
			break;
		case "label":
			actions.labelLoaded();
			break;
		case "artist":
			actions.artistLoaded();
			break;
		case "genres":
			actions.genresLoaded();
			break;
		case "artists":
			actions.artistsLoaded();
			break;
		case "labels":
			actions.labelsLoaded();
			break;
		case "myCart":
			actions.myCartLoaded();
			break;
		case "myFavorites":
			actions.myFavoritesLoaded(params[5]);
			break;
		case "myReadyDownload":
			actions.myReadyDownloadLoaded();
			break;
		case "myHistory":
			actions.myHistoryLoaded();
			break;
		case "myProfile":
			actions.myProfileLoaded();
			break;
		}
	};

	this.breadcrumbReload = function(url) {
		actions.loading("/default/breadCrumbReload", "#breadcrumb", 'url='
				+ url);
	};

	this.reloadMyNews = function() {
		actions.goToNews(1);
	};
	
	/**
	 * preload function
	 */

	this.supergenrePreLoad = function(url) {
		actions.loading("/block/switchFreshNews", ".contentDx", 'url=' + url);
	};

	/**
	 * loaded function
	 */

	this.releaseLoaded = function(id) {
		actions.releaseGrid(id);
		FB.Share.renderAll();
		gapi.plusone.go();
	};

	this.labelLoaded = function(id) {
		FB.Share.renderAll();
		gapi.plusone.go();
	};

	this.artistLoaded = function(id) {
		FB.Share.renderAll();
		gapi.plusone.go();
	};

	this.genresLoaded = function() {
		actions.browseSuperGenre();
	};

	this.artistsLoaded = function() {
		showBrowseArtist('A');
	};

	this.labelsLoaded = function() {
		showBrowseLabel('A');
	};

	this.myCartLoaded = function() {
		$('#pane1ShoppingCart').jScrollPane({
			showArrows : true
		});
	};

	this.myFavoritesLoaded = function(type) {
		switch (type) {
		case "labels":
		case "artists":
			jQuery(".myfavourites_contenidoCentralDx").jScrollPane({
				showArrows : true
			});
			break;
		case "genres":
			jQuery(".myfavourites_contenidoCentralDx_genres").jScrollPane({
				showArrows : true
			});
			break;
		}
	};

	this.myReadyDownloadLoaded = function() {
		jQuery("#pane1DownloadLibrery").jScrollPane({
			showArrows : true,
			scrollbarWidth : 10,
			scrollbarMargin : 1
		});
	};

	this.myHistoryLoaded = function() {
		showTracksHistory();
	};

	this.myProfileLoaded = function() {
		actions.myProfileSetup();
		actions.resetMyFlyzikButtons(4);
	};
	/**
	 * 
	 */

	this.jSubmit = function(nameForm) {
		jQuery(nameForm + "_form").submit(
				function() {
					var form = $(this);
					var str = form.serialize();
					var url = form.attr("action");
					var name = "#"+form.attr("name");
					jQuery.post(url, str, function(data, textStatus, jqXHR) {
						var type = jqXHR.getResponseHeader("Content-Type");
						if(type.indexOf("json")!=-1) {
							for ( var field in data) {
								$(name + "_" + field).parent().parent()
										.find(".erroralert").html(data[field]);
							}
						} else {
							$(".tabCentral").html(data);
						}
					});

					return false;
				});
	};

	this.search = function(formId) {

		// because search is a form submitted it needs to be treated differently
		// if the parameter is an integer it means it's been called from the
		// hashchange event (ready.js)
		// otherwise it's a form submitted
		var id;
		if (formId != undefined) {
			if (!isInteger(formId)) {
				/* Load form data into post variable to send to load */
				this.post.search = {};

				jQuery("#" + formId).find(":input").each(function() {
					if (this.name.match('search\[[a-zA-Z0-9_-\s]+\]')) {
						param = this.name.replace(/search|\[|\]/g, "");
						if (this.type != 'checkbox') {
							actions.post.search[param] = this.value;
						} else {
							if (jQuery(this).filter(":checked").length > 0) {
								actions.post.search[param] = this.value;
							}
						}
					}
				});

				// cache parameters
				var cache_post_search = {
					formId : formId,
					params : {}
				};

				cache_post_search.params[param] = actions.post.search[param];
				id = this.search_id;
				this.cache_posts_search[id] = cache_post_search;
				this.search_id++;
			} else {

				// get parameters cached
				id = formId;
				var cache_post_search = this.cache_posts_search[id];

				if (cache_post_search) {
					for (param in cache_post_search.params) {
						this.post.search[param] = cache_post_search.params[param];
					}
				}
			}
		} else {
			id = this.search_id;
			this.search_id++;
		}

		/*
		 * If the jqGrid is not created, load it and callreload, otherwise just
		 * call reload
		 */
		this.loading('track/search', undefined, this.post.search, function() {

		});

		this.hash("#search-" + id);

		if (formId !== undefined) {
			return false;
		}
	};

	this.advancedSearch = function(formId) {

		// because search is a form submitted it needs to be treated differently
		// if the parameter is an integer it means it's been called from the
		// hashchange event (ready.js)
		// otherwise it's a form submitted

		var id;
		if (!isInteger(formId)) {
			/* Load form data into post variable to send to load */
			this.post.search = {};
			if (formId !== undefined) {
				jQuery("#" + formId).find(":input").each(function() {
					if (this.name.match('search\[[a-zA-Z0-9_-\s]+\]')) {
						param = this.name.replace(/search|\[|\]/g, "");
						if (this.type != 'checkbox') {
							actions.post.search[param] = this.value;
						} else {
							if (jQuery(this).filter(":checked").length > 0) {
								actions.post.search[param] = this.value;
							}
						}
					}
				});

				// cache parameters
				var cache_post_search = {
					formId : formId,
					params : {}
				};

				// loop through params
				$.each(actions.post.search, function(index, value) {
					if (value) {
						cache_post_search.params[index] = value;
					}
				});

				id = this.search_id;
				this.cache_posts_search[id] = cache_post_search;
				this.search_id++;
			}

		} else {
			if (jQuery(".tabCentral").length == 0) {
				this.empty();
			}

			// get parameters cached
			id = formId;
			var cache_post_search = this.cache_posts_search[id];

			if (cache_post_search) {
				for (param in cache_post_search.params) {
					this.post.search[param] = cache_post_search.params[param];
				}
			}
		}

		/*
		 * If the jqGrid is not created, load it and callreload, otherwise just
		 * call reload
		 */
		this.loading('track/advancedSearch', undefined, actions.post.search,
				function() {
					adSearchGrid = searchGrid;
					adSearchGrid.pane = "#pane1AdvantageSearch";
					setJqGrid(adSearchGrid);
				});

		this.hash("#advancedSearch" + (id != null ? '-' + id : ''));

		if (formId !== undefined) {
			return false;
		}
	};

	/*
	 * CART FUNCTIONS TO ADD AND REMOVE ITEMS AND VIEW CART
	 */

	this.addCartTrack = function(id) {
		/* Call to action addCartTrack to add a track item into cart */
		this
				.call(
						'cart/addCartTrack',
						{
							'id' : id
						},
						function(data) {
							/*
							 * If the item is new (it doesn't exist) already
							 * update counters
							 */
							if (data.add == true) {
								jQuery("#cartHeaderItems").html(data.count);
								jQuery("#cartHeaderAmount").html(
										data.totalPrice);
							} else if (data.inRelease == true) {
								actions
										.showAlert(actions
												.translate("You have the release of the track in the shopping cart"));
							} else if (data.add == false) {
								actions
										.showAlert(actions
												.translate("The track is in the shopping cart"));
							}
						});
	};

	this.addCartRelease = function(id) {
		/* Call to action addCartRelease to add a release item into cart */
		this.call('cart/addCartRelease', {
			'id' : id
		}, function(data) {
			/* If the item is new (it doesn't exist) already update counters */
			if (data.add == true) {
				jQuery("#cartHeaderItems").html(data.count);
				jQuery("#cartHeaderAmount").html(data.totalPrice);
			}
		});
	};

	/**
	 * Removes cart item, does not matter if it is track or release
	 */
	this.removeCartItem = function(id) {
		/* Call to action removeCartItem to remove items from cart */
		this.call('cart/removeCartItem', {
			'id' : id
		}, function(data) {

			/* Update cart counters */
			jQuery("#cartHeaderItems").html(data.count);
			jQuery("#cartHeaderAmount, .totalsRight").html(data.totalPrice);

			actions.myCart();
		});
	};

	/**
	 * Remove from user session (for anonymous users)
	 */
	this.removeCartItemSession = function(track_id) {
		this.call("cart/removeCartItemSession", {
			'id' : track_id
		}, function(data) {

			/* Update cart counters */
			jQuery("#cartHeaderItems").html(data.count);
			jQuery("#cartHeaderAmount, .totalsRight").html(data.totalPrice);

			actions.myCart();
		});
	};

	this.myCart = function() {

		this.loading('cart/myCart', ".tabCentral", undefined, function() {
			jQuery("#pane1ShoppingCart").jScrollPane({
				showArrows : true
			});
			jQuery("#myCartForm").submit(function() {
				/*
				 * actions.call('paypal/validateCheckout', {credit:
				 * jQuery('input[name=credit]').val()}, function(data){ error =
				 * data; }, "html", false); if(error != 'valid' && error !==
				 * undefined){ actions.showAlert(error); return false; }
				 */
			});
			actions.resetMyFlyzikButtons(5);
		});

	};

	/*
	 * DIFERENT TRACK RELATED VIEWS (RELEASES, GENRE, ARTIST, ETC.)
	 */

	this.artistView = function(id) {
		jQuery.get("routing/artist/" + id, function(data) {
			if (data.substr(0, 6) == "error:")
				alert(data.substr(6, data.length));
			else
				window.location.href = data;
		}, 'text');
	};

	this.genreView = function(id) {
		jQuery.get("routing/genre/" + id, function(data) {
			if (data.substr(0, 6) == "error:")
				alert(data.substr(6, data.length));
			else
				window.location.href = data;
		}, 'text');
	};

	this.releaseView = function(id) {
		jQuery.get("routing/release/" + id, function(data) {
			if (data.substr(0, 6) == "error:")
				alert(data.substr(6, data.length));
			else
				window.location.href = data;
		}, 'text');
	};

	this.chartView = function(id) {
		this.loading('release/chartView', "#chartView", {
			'id' : id
		}, function() {
			actions.post.search = {
				release_id : id
			};
			setJqGrid(releaseViewGrid, this.setJqGridPostAndReload);
		});
	};

	this.releaseGrid = function(id) {
		actions.post.search = {
			release_id : id
		};
		setJqGrid(releaseViewGrid, this.setJqGridPostAndReload);
	};

	this.labelView = function(id) {
		jQuery.get("routing/label/" + id, function(data) {
			if (data.substr(0, 6) == "error:")
				alert(data.substr(6, data.length));
			else
				window.location.href = data;
		}, 'text');
	};

	this.preCheckout = function() {
		this.loading('paypal/checkout', undefined, undefined, function(data) {
			if (data == "No user") {
				actions.register({
					forward : 'paypal/checkout'
				});
			}
		});
	};

	this.checkout = function() {
		this.loading('paypal/expressCheckout', '.subtitleAzul14', {
			component : 'checkout'
		});
	};

	this.downloadLibrary = function(screen) {
		if (screen === undefined) {
			screen = 'ready';
		}

		if (screen == 'history') {
			this.loading('downloadLibrary/' + screen, undefined, undefined,
					function() {
						showTracksHistory();
					});
		} else {
			this.loading('downloadLibrary/' + screen, "#main", {}, function() {
				$('#pane1DownloadLibrery').jScrollPane({
					showArrows : true
				});

				actions.ellipsis();
			});
		}
		actions.resetMyFlyzikButtons(2);

		this.hash("#downloadLibrary-" + screen);
	};

	this.registerFromAlert = function() {
		jQuery("#modal-alert").dialog('close');

		var param = {
			'checkout' : "true"
		};

		this.register(param);
	};

	this.register = function(params) {
		var url = "/register";
		$(location).attr('href', url);
	};

	this.myProfile = function() {
		this.loading('fzApply/myProfile', undefined, undefined, function() { // '.content'
			actions.myProfileSetup();
			actions.resetMyFlyzikButtons(4);
		});
	};

	this.myProfileSetup = function(params) {
		jQuery('.submitBuy')
				.click(
						function() {
							credits = jQuery('.inputBuyCredits').val();
							if (credits.match('[0-9]+[.,]{0,1}[0-9]{0,2}')) {
								jQuery('#fz_apply_update_form').attr("action",
										baseUrl + "paypal/buyCredit");
								jQuery('#fz_apply_update_form').unbind();
							} else {
								actions
										.showAlert(actions
												.translate("You have to introduce how many credits you want to buy."));
								return false;
							}
						});
		jQuery('#buttonOn').click(function() {
			jQuery('#fzApplyUpdate_auto_download').val(1);
			jQuery('#buttonOn').attr('class', 'submitOk');
			jQuery('#buttonOff').attr('class', 'submitOff');
		});
		jQuery('#buttonOff').click(function() {
			jQuery('#fzApplyUpdate_auto_download').val(0);
			jQuery('#buttonOff').attr('class', 'submitOk');
			jQuery('#buttonOn').attr('class', 'submitOff');
		});

		jQuery('#fz_apply_update_form').unbind();
		jQuery('#fz_apply_update_form')
				.submit(
						function() {
							form = {};
							jQuery(this)
									.find(":input")
									.each(
											function() {
												if (this.type != 'checkbox') {
													form[this.name] = this.value;
												} else {
													if (jQuery(this).filter(
															":checked").length > 0) {
														form[this.name] = this.value;
													}
												}
											});

							actions
									.call(
											'fzApply/validateUpdate',
											form,
											function(data) {
												if (data == 'valid') {
													jQuery(
															"#fz_apply_apply_error")
															.hide();
													actions
															.showAlert(actions
																	.translate('Your profile has been updated correctly.'));
													actions.reloadMyNews();
												} else {
													var errorMsg = data;

													jQuery(
															"#fz_apply_apply_error")
															.html(errorMsg);

													if (errorMsg
															.indexOf("2 prefered genres") > -1) {
														jQuery(
																"#fzApplyUpdate_genre_1")
																.css(
																		"background",
																		'url("/images/registarView_bgInput_error.png")');
														jQuery(
																"#fzApplyUpdate_genre_2")
																.css(
																		"background",
																		'url("/images/registarView_bgInput_error.png")');
														jQuery(
																"#fzApplyUpdate_genre_3")
																.css(
																		"background",
																		'url("/images/registarView_bgInput_error.png")');
														jQuery(
																"#fzApplyUpdate_genre_4")
																.css(
																		"background",
																		'url("/images/registarView_bgInput_error.png")');
													}

													if (errorMsg
															.indexOf("username") > -1)
														jQuery(
																"#fzApplyUpdate_username")
																.css(
																		"background",
																		'url("/images/registarView_bgInput_error.png")');

													if (errorMsg
															.indexOf("passwords") > -1
															|| errorMsg
																	.indexOf("password wrong") > -1) {
														jQuery(
																"#fzApplyUpdate_password")
																.css(
																		"background",
																		'url("/images/registarView_bgInput_error.png")');
														jQuery(
																"#fzApplyUpdate_password2")
																.css(
																		"background",
																		'url("/images/registarView_bgInput_error.png")');
														jQuery(
																"#fzApplyUpdate_old_password")
																.css(
																		"background",
																		'url("/images/registarView_bgInput_error.png")');
														jQuery(
																'.upProfileLinea6_3')
																.show();
													}

													jQuery(
															"#fz_apply_apply_error")
															.show();
													// var si =
													// jQuery('#pane1UpdateProfle').width();
													// jQuery('#pane1UpdateProfle').width(si-10);

													var api = jQuery(
															'#pane1UpdateProfle')
															.data('jsp');
													api.reinitialise();
													api.scrollTo(0, 0, true);
												}
											}, 'html');
							return false;
						});

		jQuery('#pane1UpdateProfle').jScrollPane({
			showArrows : true,
			maintainPosition : true
		});
		if (params !== undefined && params.message !== undefined) {
			actions.showAlert(params.message);
		}
	};

	/**
	 * Playlist actions
	 */

	/**
	 * Playlist creation from selected songs in the playlist
	 */

	this.createNewPlaylist = function(songs) {
		params = {
			'songs' : songs
		};
		this.call('playlist/createNewPlaylist', params, function(data) {
			actions.editPlaylist(data);
		}, "html");
	};

	this.editPlaylist = function(id) {
		params = {
			'id' : id
		};

		this.loading('playlist/edit', undefined, params, function() {
			actions.loadPlaylist(id);
			setJqGrid(createPlaylistGrid);
			actions.setUploadify("#playlistImage", "#playlistEdit_image",
					'playlist', '*.jpg;*.gif;*.png');
			actions.savePlaylist();
		});
	};

	this.savePlaylist = function() {
		jQuery('#playlist_edit_form').submit(
				function() {
					form = {};
					jQuery(this).find(":input").each(function() {
						if (this.type != 'checkbox') {
							form[this.name] = this.value;
						} else {
							if (jQuery(this).filter(":checked").length > 0) {
								form[this.name] = this.value;
							}
						}
					});

					actions.call('playlist/validateSave', form, function(data) {
						if (data != 'valid') {
							jQuery('#playlist_edit_error').stop().html(data)
									.show().animate({
										opacity : 1.0
									}, 4000).fadeOut('slow');
						}
					});
					return false;
				});
	};

	this.loadPlaylist = function(id) {

		actions.post.search = {
			playlist_id : id
		};

		jQuery('#playlistTrackList').trigger("reloadGrid");

	};

	this.removePlaylist = function(id) {
		actions.call('playlist/remove', {
			id : id
		}, function(data) {
			actions.myPlaylists();
		});
	};

	this.setUploadify = function(id, field, folder, fileExt) {
		jQuery(id).uploadify({
			'uploader' : '/js/uploadify/uploadify.swf',
			'script' : '/js/uploadify/upload.php',
			'checkScript' : '/js/uploadify/check.php',
			'cancelImg' : '/js/uploadify/cancel.png',
			'auto' : true,
			'wmode' : 'transparent',
			'folder' : folder,
			'fileExt' : fileExt,
			'multi' : true,
			'height' : 20,
			'width' : 96,
			'hideButton' : true,
			'onCheck' : function() {
				return false;
			},
			'onError' : function(event, queueID, fileObj, errorObj) {
				jQuery("#uploadify_error").show();
			},
			'onComplete' : function(event, queueID, fileObj, response, data) {
				jQuery(field).val(response);
				jQuery("#uploadify_success").show();
			}
		});
		jQuery('#playlistImage').show();
	};
	/**
	 * Favorites functionalities
	 */

	/**
	 * My favorites page
	 */

	this.myFavorites = function(type, args) {

		if (type === undefined) {
			type = 'intro';
		}

		this.loading('myFavorites/' + type, undefined, undefined, function() {
			switch (type) {
			case 'releases':
				showTracksFromReleases();
				jQuery(".myfavourites_contenidoCentral_releaseDx").jScrollPane(
						{
							showArrows : true
						});
			case 'tracks':
				if (args !== undefined) {
					actions.post.search = {
						favorite_id : args.user
					};
				}
				setJqGrid(trackFavoriteGrid);
				break;
			case 'labels':
				jQuery(".myfavourites_contenidoCentralDx").jScrollPane({
					showArrows : true
				});
			case 'genres':
				jQuery(".myfavourites_contenidoCentralDx_genres").jScrollPane({
					showArrows : true
				});
			case 'artists':
				jQuery(".myfavourites_contenidoCentralDx").jScrollPane({
					showArrows : true
				});
			default:
				jQuery(".myfavourites").jScrollPane({
					showArrows : true
				});
			}

			actions.resetMyFlyzikButtons(1);
		});

		this.hash("#myFavorites");
	};

	this.blockUI = function() {
		jQuery.blockUI({
			css : {
				border : 'none',
				padding : '15px',
				backgroundColor : '#fff',
				'-webkit-border-radius' : '10px',
				'-moz-border-radius' : '10px',
				opacity : .8,
				color : '#000',
				width : '200px',
				left : '80px'
			},
			message : '<p><strong>Please, wait...</strong></p>',
			fadeIn : 700,
			fadeOut : 700
		});
	};

	this.getUrl = function(url, callback) {
		this.blockUI();
		jQuery.get(url, function(data) {
			if (callback !== undefined) {
				callback(data);
			}
			$.unblockUI();
		});
		$.unblockUI();
	};

	/*
	 * Favorites
	 */
	
	
	/**
	 * Add a label to the user favorites
	 */
	this.addLabelToFavorites = function(label_id) {
		if (label_id == undefined)
			return false;
		else
			this.getUrl(baseUrl + "myFavorites/addLabel/" + label_id,
							function(data) {
								switch (code) {
								case "0":
									actions.showAlert("You already have the label as favorite");
									break;
								case "1":
									break; // OK
								default:
									actions.showNotRegistered();
									break;
								}
							});

	};

	/**
	 * Add a track to the user favorites
	 */
	this.addTrackToFavorites = function(track_id) {
		if (track_id == undefined)
			return false;
		else
			this
					.getUrl(
							baseUrl + "myFavorites/addTrack/" + track_id,
							function(data) {
								code = data.charAt(0);
								switch (code) {
								case "0":
									actions
											.showAlert("You already have the track as favorite");
									break;
								case "1":
									break; // OK
								default:
									actions.showNotRegistered();
									break;
								}
							});
	}

	/**
	 * Add a release to the user favorites
	 */
	this.addReleaseToFavorites = function(release_id) {
		if (release_id == undefined)
			return false;
		else
			this
					.getUrl(
							baseUrl + "myFavorites/addRelease/" + release_id,
							function(data) {
								code = data.charAt(0);
								switch (code) {
								case "0":
									actions
											.showAlert("You already have the release as favorite");
									break;
								case "1":
									break; // OK
								default:
									actions.showNotRegistered();
									break;
								}
							});

	};

	/**
	 * Add an artist to the user favorites
	 */
	this.addArtistToFavorites = function(artist_id) {
		if (artist_id == undefined)
			return false;
		else
			this
					.getUrl(
							baseUrl + "myFavorites/addArtist/" + artist_id,
							function(data) {
								code = data.charAt(0);
								switch (code) {
								case "0":
									actions
											.showAlert("You already have the artist as favorite");
									break;
								case "1":
									break; // OK
								default:
									actions.showNotRegistered();
									break;
								}
							});

	}

	/**
	 * Add a genre to the user favorites
	 */
	this.addGenreToFavorites = function(genre_id) {
		if (genre_id == undefined)
			return false;
		else
			this
					.getUrl(
							baseUrl + "myFavorites/addGenre/" + genre_id,
							function(data) {
								code = data.charAt(0);
								switch (code) {
								case "0":
									actions
											.showAlert("You already have the genre as favorite");
									break;
								case "1":
									break; // OK
								default:
									actions.showNotRegistered();
									break;
								}
							});

	};

	this.load = function(url, where, from, params, callback) {
		/* Load default variables if undefined */
		if (where === undefined) {
			where = ".tabCentral";
		}
		// empty, for standard from we have the loadUrl function.
		if (from === undefined) {
			from = "";
		} else {
			from = " " + from;
		}

		if (params === undefined) {
			params = {};
		}
		params.ajax = true;
		/* Ajax load of data */
		jQuery(where).load(baseUrl + url + from, params,
				function(responseText, textStatus, XMLHttpRequest) {
					if (callback !== undefined) {
						callback(responseText, textStatus, XMLHttpRequest);
					}
					actions.ellipsis();
					actions.click(where);

				});
	};

	/**
	 * load is for actions without layout
	 */
	this.loadUrl = function(url, where, params, callback) {

		/* Load default variables if undefined */
		if (where === undefined) {
			// where = ".tabCentral";
			where = "#main";
		}

		if (where == ".content" || where == "#myNewReleasesSet"
				|| where == "#freshNewsSet" || where == "#releasesLabel"
				|| where == "#releasesGenre" || where == "#releasesArtist"
				|| where == "#topSet" || where == "#searchResults"
				|| where == "#twoWeeks" || where == "#favoriteReleases"
				|| where == "#chartView" || where == ".tabCentral")
			get = "";
		else
			get = " #main > div";

		if (params === undefined) {
			params = {};
		}
		var showtab = params.showtab;
		delete params.showtab;
		params.ajax = true;

		/* Ajax load of data */
		var activedTab = $(".actived").attr("href");

		jQuery(where).load(baseUrl + url + get, params,
				function(responseText, textStatus, XMLHttpRequest) {
					if (callback !== undefined) {
						callback(responseText, textStatus, XMLHttpRequest);
					}

					actions.click(where);

					if (showtab)
						actions.showTab(activedTab);

				});

		if (where != "#breadcrumb" && where != "#freshNewsSet"
				&& where != ".tabCentral") // Refresh breadcrumb
			actions.breadcrumb();
	};

	this.showTab = function(tab) {
		var tabsContainers = $('div.tabsContainers > div');
		tabsContainers.hide().filter(tab).show();
		$('div.tabsContainers ul.tabsNavigation a').removeClass('actived');
		var id = tab.charAt(tab.length - 1);
		$('#lastTab' + id + ' a').addClass('actived');
	};

	this.call = function(action, params, callback, type, async) {
		/* Ajax call to action, returns json */
		if (type === undefined) {
			type = "json";
		}
		if (async === undefined) {
			async = false;
		}
		if (params === undefined) {
			params = {};
		}
		params.ajax = true;
		jQuery.ajax({
			type : 'POST',
			url : baseUrl + action,
			data : params,
			async : async,
			success : function(data) {
				if (callback !== undefined) {
					callback(data);
				}
			},
			dataType : type
		});
	};

	/**
	 * This method show an alert, it would be good use another form to show
	 * messages to the client instead "alert"
	 */
	this.showAlert = function(data) {
		jQuery("#modal-alert").html(
				'<div class="overlaypayment_content">' + data + "</div>");
		jQuery("#modal-alert").dialog("open");
	};

	this.showTempAlert = function(data, delay) {
		jQuery('#modal-alert').dialog({
			autoOpen : false,
			modal : true
		});
		$("#modal-alert").dialog({
			closeOnEscape : false,
			open : function(event, ui) {
				$(".ui-dialog-titlebar-close").hide();
			}
		});
		jQuery("#modal-alert").html(
				'<div class="overlaypayment_content">' + data + "</div>");
		jQuery("#modal-alert").dialog("open");
		window.setTimeout(function() {
			jQuery("#modal-alert").dialog("close");
		}, delay);
	};

	this.showNotRegistered = function() {
		jQuery("#not_registered").dialog("open");
	};

	/**
	 * This method makes a request to the server to translate a text.
	 */

	this.translate = function(text) {
		this.call('default/translate', {
			'text' : text
		}, function(data) {
			if (data != null) {
				text = data;
			}
		}, "html", false);

		return text;
	};

	/*
	 * Browse Panel
	 */

	this.browseArtist = function(item) {

		if (item == undefined) {
			item = "A";
		}

		this.loading('browse/artist/index/' + item, ".tabCentral", undefined,
				function() {
					showBrowseArtist(item);
				});

	};

	this.browseLabel = function(item) {
		if (item == undefined) {
			item = "A";
		}

		this.loading('browse/label/index/' + item, '.tabCentral', undefined,
				function() {
					showBrowseLabel(item);
				});

	};

	this.browseGenre = function() {
		this.loading('browse/browseGenres', ".tabCentral", undefined,
				function() {
					showBrowseGenre();
				});
	};

	this.browseSuperGenre = function() {
		this.loading('browse/browseGenres', ".tabCentral", undefined,
				function() {
					showBrowseSuperGenre();
				});
	};

	/*
	 * Reset global stuff which broken on some loads
	 */

	this.reset = function() {
		var tabsContainers = $('div.tabsContainers > div');
		$('div.tabsContainersUP ul.tabsNavigation a').click(
				function() {
					// ALB: this.hash?!?
					tabsContainers.hide().filter(this.hash).show();
					$('div.tabsContainersUP ul.tabsNavigation a').removeClass(
							'actived');
					$(this).addClass('actived');
					return false;
				}).filter(':first').click();

	};

	this.resetMyFlyzikButtons = function(number) {
		jQuery(".contentBoxMyFlyzik .icons a").removeClass("on");
		jQuery(".contentBoxMyFlyzik .icons a:nth-child(" + number + ")")
				.addClass("on");
	};

	/**
	 * Used in release view
	 */
	this.ranking = function(value) {

		// Deactivate the images
		for (i = 1; i < 6; i++) {
			if (i != value) {
				jQuery("#ranking_" + i).attr("src",
						baseUrl_root + '/images/ranking/' + i + '.png');
			}
		}

		// Activate the image
		jQuery("#ranking_" + value).attr("src",
				baseUrl_root + '/images/ranking/' + value + '_deactivated.png');

		// Put the value
		jQuery("#comment_rate").val(value);
	}

	/**
	 * Download the track and activate the next
	 */
	this.downloadTrack = function(id, idNext) {
		$("#downloadFile_" + id).attr("src", baseUrl + 'download/' + id);

		$("#cartItem_" + id).fadeOut(10000);

		if (idNext != 'undefined') {
			$("#imgDeac_" + idNext).hide();
			$("#img_" + idNext).fadeIn();
		}

		/*
		 * // Hidden the footer if there aren't more tracks var allHidden =
		 * true; jQuery("tr[id^='cartItem_']").each( function(intIndex){ if
		 * ($(this).attr("id").substring(9) != id && $(this).is(':visible')){ //
		 * With fadeOut continuous being visible allHidden = false; return
		 * false; } } );
		 * 
		 * if (allHidden) jQuery("#checkout_footer").fadeOut();
		 */

		if (idNext == "undefined")
			jQuery("#checkout_footer").fadeOut();
	};

	this.downloadRelease = function(id) {
		window.open(baseUrl + 'getrelease/' + id);
		this.downloadLibrary('ready');
	};

	this.searchGlobal = function(text) {
		jQuery("#search_global").val(text);

		return this.search("searchForm");
	};

	/**
	 * ajax pager
	 */

	this.goToNews = function(page) {
		jQuery("#myNewReleasesSet").empty().html(
				'<img src="/images/loading.gif" class="loading" />');

		this.loading("block/myNewReleasesAjax/" + page, "#myNewReleasesSet");

	};

	this.goToFreshNews = function(page) {
		jQuery("#freshNewsSet").empty().html(
				'<img src="/images/loading.gif" class="loading" />');

		this.loading("block/freshNewsAjax", "#freshNewsSet", {
			'page' : page
		});
	};

	this.releasesLabel = function(label_id, page) {
		this.loading("block/releasesLabelAjax", "#releasesLabel", {
			'id' : label_id,
			'page' : page
		});
	};

	this.releasesGenre = function(genre_id, page) {
		this.loading("block/releasesGenreAjax", "#releasesGenre", {
			'id' : genre_id,
			'page' : page
		});
	};

	this.chartsGenre = function(page) {
		jQuery("#releasesGenre").load(baseUrl + "block/chartsGenreAjax/", {
			'page' : page
		}, function() {
		});
	};

	this.resultsSearch = function(term, page) {
		this.loading("block/resultsSearchAjax", "#searchResults", {
			'global' : term,
			'page' : page
		});
	};

	this.favoriteReleases = function(page) {
		this.loading("block/favoritesReleasesAjax", "#favoriteReleases", {
			'page' : page
		});
	};

	this.searchRemix = function(remix) {
		if (remix) {
			var arr = remix.split(" ");
			var text = "";

			for ( var i = 0; i < arr.length - 1; i++)
				// Quit the last word
				text += arr[i] + " ";

			jQuery("#search_global").val(text);
			this.search("searchForm");
		}
	};

	this.hash = function(href) {
		var hash = location.hash;
		// it could be called twice (ex: default/empty and release/artistView)
		if ((encodeURI(hash) != href) & !(hash == '' & href == '#')) {
			var url = location.href.split("#")[0];
			var lhref = url + href;
			this.cache[lhref] = lhref;
			location.href = lhref;
		}
	};

	this.empty = function() {
		this
				.load(
						'default/empty',
						'.bg',
						'.bg > div',
						undefined,
						function() {
							// WARNING: this bit is not being executed
							// Load player
							var params = {};
							params.swliveconnect = "true";
							params.allowScriptAccess = "sameDomain"; // allways
							params.quality = "high";
							params.wmode = "transparent";
							params.FlashVars = "small=true&demo=false&user_id=<?php echo session_id() ?>";
							var attributes = {
								id : "audioPlayer",
								name : "audioPlayer",
								align : "middle"
							};
							swfobject
									.embedSWF(
											"/swf/audioPlayer.swf?small=true&demo=false",
											"player", "815", "37", "10.0.0",
											null, null, params, attributes);
							// load player - end
						});
	};

	function isInteger(s) {
		if (s == undefined)
			return false;

		return (s.toString().search(/^-?[0-9]+$/) == 0);
	}

	/**
	 * Add downloads+1 in the list tracks separated for "," to the user
	 */
	this.downloadFromZip = function(l_tracks) {
		var url = baseUrl + 'sales/addDownloads?tracks=' + l_tracks;

		jQuery.get(url, {}, function(data) {
		});
	};

	this.goTo2WeeksSelection = function(page) {
		jQuery("#twoWeeks_releases").empty().html(''); // Clear screen

		this.loading("axdxvx/twoWeeksAjax/" + page, "#twoWeeks", undefined,
				function() {
					actions.ellipsis()
				});
	};

	/**
	 * The param indicates if the button will be hidden
	 */
	this.downloadAll = function() {

		actions.showAlert("Please, wait until we prepare the ZIP file for you");

		var url = baseUrl + "default/downloadAll";

		$("#downloadFile").attr("src", url);

		var url = baseUrl + "json/ajaxTracksReadyToDownload";
		var vIds = new Array();
		var found = false;
		jQuery.get(url, {}, function(data) {
			vIds = data.split(",");
			for ( var i in data) {
				id = vIds[i];
				if (id != undefined) {
					jQuery("#cartItem_" + id).fadeOut();
				}
			}

			// Put the new to download active
			/*
			 * $(".cartItem").each(function(){ var id = $(this).attr("id"); var
			 * index = id.substring(id.indexOf("_")+1); if
			 * (!jQuery.inArray('"'+index+'"', vIds)){ $("#imgDeac_" +
			 * index).hide(); $("#img_" + index).fadeIn(); found = true; return
			 * false; } });
			 */

		});

	};

	this.ellipsis = function() {
		// classname ellipse => 1 row, ellipse2 => 2 rows, etc
		/*
		 * $('[class^="ellipse"]').each(function() { // get class names a we
		 * could have more than one var arrClasses =
		 * $(this).attr("class").split(" "); // loop through var rows = 0; var
		 * objRegExp = /^ellipse(([0-9])?)$/; $.each(arrClasses, function(index,
		 * value) { if (value.match(objRegExp) != null) { rows = RegExp.$1 == '' ?
		 * 1 : RegExp.$1;
		 * 
		 * return false; // break } });
		 * 
		 * if (rows) { if ($(this).children("span.threedots_ellipsis").size() ==
		 * 0) { $(this) .wrapInner('<span class="ellipsis_text" />')
		 * .ThreeDots({ max_rows: rows, whole_word: false, alt_text_e:true,
		 * alt_text_t:true }); } } });
		 */
	};

}

var actions = new Actions();

//Google Analytics
var _gaq = _gaq || [];
_gaq.push([ '_setAccount', 'UA-19182645-2' ]);
_gaq.push([ '_setDomainName', 'none' ]);
_gaq.push([ '_setAllowLinker', true ]);
_gaq.push([ '_trackPageview' ]);

(function() {
	var ga = document.createElement('script');
	ga.type = 'text/javascript';
	ga.async = true;
	ga.src = ('https:' == document.location.protocol ? 'https://ssl'
			: 'http://www')
			+ '.google-analytics.com/ga.js';
	var s = document.getElementsByTagName('script')[0];
	s.parentNode.insertBefore(ga, s);
})();

