skatic.allowedToExecute = ['afterLogin', 'afterLogout', 'tb_remove', 'albumAddSuccessOnAddSong', 'albumAddSuccessOnManageSongs', 'albumEditSuccessOnManageSongs', 'addSongsErrors', 'sendInvitesErrors', 'sendRecommendErrors', 'addPhotosErrors', /*'photoAlbumAddSuccessOnAddPhoto',*/ 'resizeEnd'/*, 'equipmentSortSuccess'*/, 'reloadCaptcha', 'playlistAddSuccess', 'getUnreadPmCount', 'removePlaylistRecord', 'removePlaylistSucess', 'invalidateFields', 'playBySongId', 'addEquipmentTypeEnd', 'afterChangeLocale'];
skatic.executeMethods = [];


skatic.executeMethods.tb_remove = function(refresh, redirect, flash) {
  self.parent.tb_remove();
  if (typeof flash != 'undefined') {
    self.parent.skatic.flash(flash);
  }
  if (typeof refresh != 'undefined' && refresh == 'refresh') {
    self.parent.skatic.refreshPage();
  }
  if (typeof redirect != 'undefined' && redirect != null && redirect != '') {
    self.parent.skatic.redirect(redirect);
  }
};

skatic.executeMethods.invalidateFields = function(errors) {
  skatic.invalidateFields(errors);
  skatic.executeMethods.reloadCaptcha();
};

skatic.executeMethods.afterLogin = function(email, slug, screenName, avatar, role) {
  var innerHtml = '<a href="#/'+slug+'/">'
  //innerHtml += '<img src="'+avatar+'" alt="'+screenName+'" class="left profimg" /></a>';
  innerHtml += '<a href="#/'+slug+'/">'+screenName+'</a>';
  $('#welcomeTextUsername').html(innerHtml);

  $('#loginbox').hide();
  $('#menuLoginLink').hide();
  $('#menuRegistrationLink').hide();
  $('#menuLogoutLink').show();

  $('#profilemenu').show();

  /*setTimeout(function(){
    $.ajax({
      'url':'/playlists/userPlaylists/?locationChanged=false',
      'type':'GET',
      'cache':false,
      'success':function(response){
        $('#addplaylist ul').remove();
        $('#addplaylist a[title*="Add"]').before(response);
      },
      'dataType':'html'
    });
  }, 750);*/

  $.ajax({
    'url':'/users/profilemenu/?locationChanged=false',
    'type':'GET',
    'cache':false,
    'success':function(response){
      $('#profilemenu_expanded').replaceWith(response);
    }
  });

  if (role == 'ADMINISTRATOR') {
    $.ajax({
      'url':'/users/adminMenu/ADMINISTRATOR/?locationChanged=false',
      'type':'GET',
      'success':function(response) {
        $('#nav').after(response);
      }
    });
  } else if (role == 'EDITOR') {
    $.ajax({
      'url':'/users/adminMenu/EDITOR/?locationChanged=false',
      'type':'GET',
      'success':function(response) {
        $('#nav').after(response);
      }
    });
  }

  setTimeout(function(){
    skatic.menu.editPlaylists.ajaxLoadMenu();
  }, 3000);


  setTimeout(skatic.appliedAjaxMethods.getUnreadPmCount, 120000); //2 mins
};

skatic.executeMethods.afterLogout = function(email, slug) {
  $('#welcomeTextUsername').html(''); //'Unregistered Guest'
  $('#menuLoginLink').show();
  $('#menuRegistrationLink').show();
  $('#menuLogoutLink').hide();
  $('#profilemenu').hide();
  $('#adminmenu').remove();

  setTimeout(function(){
    //skatic.menu.editPlaylists.ajaxLoadMenu();
  }, 3000);
};



skatic.executeMethods.afterChangeLocale = function(){
	skatic.refreshPage();

	$.ajax({
		'url': '/systems/reloadLayout/',
		'type': 'get',
		'cache': false,
		'dataType': 'json',
		'success': function(response){
			for (var selector in response) {
				$(selector).replaceWith(response[selector]);
			}

			setTimeout(function(){
				skatic.layoutReady();
			}, 500);
		}
	});
};



skatic.executeMethods.albumAddSuccessOnAddSong = function(id, name, incId) {
//	console.log(id, name, incId, 'Song'+incId+'AlbumId', self.parent.document.getElementById('Song'+incId+'AlbumId'));
  var currSelect = self.parent.document.getElementById('Song'+incId+'AlbumId');

  if (currSelect) {
    $(currSelect).parents('form').find('label span:hidden').show();
    $(currSelect).parents('form').find('select:hidden').show();

    var selects = $(currSelect).parents('form').find('select');

    selects.each(function(){

      if (this.id.match('Song.*AlbumId')) {

        $(this).append('<option value="'+id+'">'+name+'</option>');

        //selectedIndex does not work, I don't know why
        $(this).find('option:selected').removeAttr('selected');
        $(this).find('option[value='+id+']').attr('selected', 'selected');
      }
    });

  }


  self.parent.tb_remove();
};

skatic.executeMethods.albumAddSuccessOnManageSongs = function(id, name, thumb) {
  /*var hiddenTrHtml = $(self.parent.document).find('#manage_albums_table #hidden_tr').html();
  var newTrHtml = hiddenTrHtml.replace('ALBUMID', id, 'g').replace('THUMBSRC', thumb, 'g').replace('ALBUMNAME', name, 'g');

  $(self.parent.document).find('#manage_albums_table').append('<tr>'+newTrHtml+'</tr>').show();
  $(self.parent.document).find('#noAlbums').remove();

  skatic.ajax.replaceLinksWithAnchors();

  self.parent.tb_remove();*/
  /**
   * @since lightbox from /songs/my/ page
   */
  skatic.executeMethods.tb_remove('refresh');
};

skatic.executeMethods.albumEditSuccessOnManageSongs = function(id, name, thumb) {
  /*$(self.parent.document).find('#manage_albums_table #album_td_'+id).html('<img src="'+thumb+'" class="userpic left" /><h5>'+name+'</h5>');

  $(self.parent.document).find('#manage_albums_table').show();
  $(self.parent.document).find('#noAlbums').remove();

  self.parent.tb_remove();*/
  /**
   * @since lightbox from /songs/my/ page
   */
  /*var albumDiv = $(self.parent.document).find('#album_'+id);
  var h2 = albumDiv.find('h2');
  h2.find('span').html(name);
  h2.find('img').attr('src', thumb);*/

  skatic.executeMethods.tb_remove('refresh');
};

/*skatic.executeMethods.photoAlbumAddSuccessOnAddPhoto = function(id, name, photoId) {
  $('select[name$="[photo_album_id]"]').append('<option value="'+id+'">'+name+'</option>');

  if ($('#Photo'+photoId+'PhotoAlbumId').length > 0) {
    //selectedIndex does not work, I don't know why
    $('#Photo'+photoId+'PhotoAlbumId option:selected').removeAttr('selected');
    $('#Photo'+photoId+'PhotoAlbumId option[value='+id+']').attr('selected', 'selected');
  }

  tb_remove();
}*/

skatic.executeMethods.addSongsErrors = function(incIdsWithErrors, errors) {
  //console.log(incIdsWithErrors);
  $('.error-message').remove();

  $('fieldset[id^="fieldset_"]').each(function(){
    //console.log(this);
    var incId = this.id.split('_')[1];
    if (incId == 'incId') {
      return;
    }

    //console.log(incIdsWithErrors);

    if (incIdsWithErrors.indexOf(parseInt(incId)) == -1) {
      $(this).remove();
    }
  });

  skatic.invalidateFields(errors);
  //$('#spanButtonPlaceholder_'+value.incId).html(value.filename+' uploaded');
};

skatic.executeMethods.addPhotosErrors = function(idsWithErrors, errors) {
  //console.log(idsWithErrors);
  $('.error-message').remove();

  $('div[id^="photo_"]').each(function(){
    //console.log(this);
    var id = this.id.split('_')[1];
    if (id == 'PHOTOID') {
      return;
    }

    if (idsWithErrors.indexOf(parseInt(id)) == -1) {
      $(this).remove();
    }
  });

  skatic.invalidateFields(errors);
};

skatic.executeMethods.sendInvitesErrors = function(incIdsWithErrors, errors) {
  //console.log(incIdsWithErrors);
  $('.error-message').remove();

  $('div[id^="div_invite_"]').each(function(){
    //console.log(this);
    var incId = this.id.split('_')[2];
    if (incId == 'incId') {
      return;
    }

    if (!incIdsWithErrors.in_array(parseInt(incId))) {
      //console.log('remove');
      $(this).remove();
    }
  });

  skatic.invalidateFields(errors);
};

skatic.executeMethods.sendRecommendErrors = function(incIdsWithErrors, errors) {
  //console.log(incIdsWithErrors);
  $('.error-message').remove();

  $('div[id^="div_recommend_"]').each(function(){
    //console.log(this);
    var incId = this.id.split('_')[2];
    if (incId == 'incId') {
      return;
    }

    if (!incIdsWithErrors.in_array(parseInt(incId))) {
      //console.log('remove');
      $(this).remove();
    }
  });

  skatic.invalidateFields(errors);
};

skatic.executeMethods.reloadCaptcha = function(){
  $('img[src*="/captcha/"], img[src*="/captchaSimple/"]').each(function(){
    var src = this.src;
    var match = src.match(/_=([0-9\.]+)/);
    if (match != null) {
      $(this).attr('src', src.replace(match[1], Math.random()));
    } else {
      if (src.indexOf('?') == -1) {
        $(this).attr('src', src+'?_='+Math.random());
      } else {
        $(this).attr('src', src+'&_='+Math.random());
      }
    }
  });
};

skatic.executeMethods.resizeEnd = function(model, field, id, resizedFiles, namedParams) {
//	console.log('skatic.executeMethods.resizeEnd called!');

  setTimeout(function(){
//		console.log(model, field, id, resizedFiles, namedParams);

    skatic.executeMethods.resizeEndSpecified[model][field](id, resizedFiles, namedParams);

  }, 1000);
};

skatic.executeMethods.resizeEndSpecified = {};

skatic.executeMethods.resizeEndSpecified.BlogPost = {
  'image': function(id, data, params) {

    //self.parent.console.info(id, data, params);

    $(self.parent.document).find('#'+params.versionsHiddenId).val(escape(JSON.stringify(data.versionsHidden)));
    $(self.parent.document).find('#'+params.outDimensionsId).val(escape(JSON.stringify(data.outDimensions)));

    if (typeof data.thumbnail != 'undefined' && data.thumbnail != null) {
      $(self.parent.document).find('#'+params.thumbImageId).attr('src', data.thumbnail).show();
    }

    self.parent.tb_remove();
  }
};

skatic.executeMethods.resizeEndSpecified.Profile = {
  'header_photo': function(id, resizedFiles, namedParams) {
    $.ajax({
      'url':'/profiles/upload/header_photo/'+id+'/',
      'type':'POST',
      'data':{'large':resizedFiles.large},
      'cache':false,
      'dataType':'json',
      'success':function(response){
        skatic.ajaxResponse(response);

        var preloader = new Image();
        preloader.onload = function() {
          $(self.parent.document).find('.profile-image').attr('src', response.profile.header_photo.large);
          setTimeout(function(){skatic.bgImage.scale();}, 50);
          setTimeout(function(){skatic.executeMethods.tb_remove(false);}, 200);
        };
        preloader.src = response.profile.header_photo.large;
      }
    });
  },
  'avatar': function(id, resizedFiles, namedParams) {
//		console.log('skatic.executeMethods.resizeEndSpecified.Profile.avatar called!');

    var responseFunction = function(response){
      response = JSON.parse(response);
//			console.log(response);

      var host = document.location.protocol+'//'+document.location.host;

      if (typeof skatic.siteStorage['avatarNew200Src'] == 'undefined') {
        new200Src = [response.profile.avatar.new200];
      } else {
        new200Src.push(response.profile.avatar.new200);
      }
      if (typeof skatic.siteStorage['avatarLargeSrc'] == 'undefined') {
        largeSrc = [response.profile.avatar.large];
      } else {
        largeSrc.push(response.profile.avatar.large);
      }
      if (typeof skatic.siteStorage['avatarThumbSrc'] == 'undefined') {
        thumbSrc = [response.profile.avatar.thumb];
      } else {
        thumbSrc.push(response.profile.avatar.thumb);
      }



      for (var i = 0; i < new200Src.length; i++) {
//				console.log('img[src="'+largeSrc[i]+'"], img[src="'+host+largeSrc[i]+'"], img[src="'+host+response.profile.avatar.large+'"]');
        var new200 = $(self.parent.document).find('img[src="'+new200Src[i]+'"], img[src="'+host+new200Src[i]+'"], img[src="'+host+response.profile.avatar.new200+'"]');
        new200.attr('src', '/files/uploaded/'+resizedFiles.new200);
      }
      for (var i = 0; i < largeSrc.length; i++) {
//				console.log('img[src="'+largeSrc[i]+'"], img[src="'+host+largeSrc[i]+'"], img[src="'+host+response.profile.avatar.large+'"]');
        var large = $(self.parent.document).find('img[src="'+largeSrc[i]+'"], img[src="'+host+largeSrc[i]+'"], img[src="'+host+response.profile.avatar.large+'"]');
        large.attr('src', '/files/uploaded/'+resizedFiles.large);
      }
      for (var i = 0; i < thumbSrc.length; i++) {
//				console.log('img[src="'+thumbSrc[i]+'"], img[src="'+host+thumbSrc[i]+'"], img[src="'+host+response.profile.avatar.thumb+'"]');
        var large = $(self.parent.document).find('img[src="'+thumbSrc[i]+'"], img[src="'+host+thumbSrc[i]+'"], img[src="'+host+response.profile.avatar.thumb+'"]');
        large.attr('src', '/files/uploaded/'+resizedFiles.thumb);
      }

      largeSrc.push('/files/uploaded/'+resizedFiles.large);
      thumbSrc.push('/files/uploaded/'+resizedFiles.thumb);
      new200Src.push('/files/uploaded/'+resizedFiles.new200);

      $(self.parent.document).find('#avatar_image img').attr('src', '/files/uploaded/'+resizedFiles.new200);

      skatic.siteStorage['avatarnew200Src'] = new200Src;
      skatic.siteStorage['avatarLargeSrc'] = largeSrc;
      skatic.siteStorage['avatarThumbSrc'] = thumbSrc;

//			var iframeSrc = '/resizes/reloadIframe/Profile/avatar/'+response.id+'/';
//			$(self.parent.document).find('#content').append('<iframe src="'+iframeSrc+'" width="1" height="1" style="width:1px;height:1px;position:absolute;top:-10000px;"></iframe>');
//			self.parent.setTimeout("self.parent.frames[0].window.location.reload(true)", 3500);
//			self.parent.setTimeout("$(self.parent.document).find('iframe').remove();", 6000);

      self.parent.skatic.user.id = response.id;
      self.parent.skatic.user.avatarUrl = {'thumb':'/profiles/avatar/'+response.id+'/thumb/','new200':'/profiles/avatar/'+response.id+'/new200/','large':'/profiles/avatar/'+response.id+'/large/'};
      self.parent.skatic.onContentShow.persist.push('skatic.user.liveAvatarUrl');

      skatic.ajaxResponse(response);
      skatic.executeMethods.tb_remove(false);
    };

    $.ajax({
      'url':'/profiles/upload/avatar/'+id+'/new200:'+resizedFiles.new200+'/large:'+resizedFiles.large+'/thumb:'+resizedFiles.thumb+'/',
      'type':'GET',
      'cache':false,
//			'data':"jsoncallback=?",
//            'dataType': "json",
//            'timeout': 1000,
      'success':function(response){
        responseFunction(response);
      }
    });
  }
};

skatic.executeMethods.playlistAddSuccess = function(newPlaylist) {
  if (self.parent.document.location.hash.indexOf('/playlists/') != -1) {
    var reloadLocation = self.parent.document.location.hash.substr(1).replace('add:true', '').replace('//', '/');
  } else {
    var reloadLocation = null;
  }

  skatic.menu.editPlaylists.ajaxLoadMenu(function(){
    //on ready callback
      skatic.executeMethods.tb_remove(null, reloadLocation);
  });
};

skatic.executeMethods.getUnreadPmCount = function() {
  skatic.appliedAjaxMethods.getUnreadPmCount(false);
};

skatic.executeMethods.removePlaylistRecord = function(result, playlistId, songId, recordId, message) {
  if (result == 'success') {
    $('#record_'+recordId).remove();
    changePlaylistOrder(playlistId);

    if ($('#playlist_'+playlistId+' li').length == 0) {
      $('#playlist_'+playlistId).append('<li id="empty_'+playlistId+'" style="padding:10px 0px 10px 10px;"><strong>Playlist is empty.</strong></li>');
    }
  }
};

skatic.executeMethods.removePlaylistSucess = function(playlistId) {
  $('#add_playlist_'+playlistId).remove();
  setTimeout(function() {
    skatic.menu.editPlaylists.ajaxLoadMenu();
  }, 1000);
};

skatic.executeMethods.playBySongId = function(songId) {
  return skatic.player.playBySongId(songId);
};

skatic.executeMethods.addEquipmentTypeEnd = function(addedTypeId, addedTypeName, flashMessage) {
  self.parent.skatic.flash([flashMessage, 'alert']);

  var select = $(self.parent.document).find('#EquipmentEquipment_type_id');
  if (select.length == 0) {
    return skatic.executeMethods.tb_remove('refresh');
  }
  if (select.find('option[value="'+addedTypeId+'"]').length == 0) {
    select.append('<option value="'+addedTypeId+'">'+addedTypeName+'</option>');
  }
  setTimeout(function(){ select.val(addedTypeId); }, 50);
  setTimeout(function(){ skatic.executeMethods.tb_remove(); }, 100);
}

