
var hn = window.location.hostname;
if(hn == "blogtest.activevos.com") {
	var remote_sites = new Array(
		'http://staging.activevos.com'
	);
}else{
	var remote_sites = new Array(
		'http://activevos.com'
	);

}

//the folder which contains the login directory
var script_root = '/';

var clicked_id;

var anonymous_links = "<a href=\"#\" onclick=\"MyPopup.width=300;MyPopup.showAjaxModalWindow('"+script_root+"login/login.html', 'GET'); return false;\">login</a>";
var logged_in_links = '<a href="#" onclick="UserAPI.logout(); return false;">logout</a>';
var loader = "<div align=\"right\"><div style=\"background: url("+script_root+"login/image/loader.gif)  no-repeat left center; width: 70px; height: 18px\">Loading...</div></div>";

$(document).ready(function() {
//  var cookie = "restoken=; Expires=Tuesday, 01-Jan-00 11:00:11 GMT; path=/";
//  cookie = encodeURIComponent( cookie );
//  for ( var j in remote_sites ) {
//    $('body').append('<iframe class="remote_logout" src="' + remote_sites[j] + '/login/setcookie.php?c=' + cookie + '" style="display: none"></iframe>');
//  }
  //setTimeout("window.location.reload();", 500);
  UserAPI.state();
});

function almost_done() {
  var html  = "<h2>Almost Done</h2>";
      html += "<br />\n";
      html += "Thank you for registering with Active Endpoints. To complete your registration you need to activate your account.  Please check your inbox (or junk folder) for an email from <a href=\"mailto:info@activevos.com\">info@activevos.com</a> and click or visit the confirmation link contained within it.";
      html += "<br />\n";
      html += "<br />\n";
      html += "<br />\n";
      html += "<br />\n";
  MyPopup.width=300;
  MyPopup.showModalWindow(html);
}

function login_unverified() {
  var html  = "<h2>Unable to login</h2>";
      html += "<br />\n";
      html += "<p>You have not yet activated your account.</p>";
      html += "<p>To activate it click or visit the link embedded in the email sent from <a href=\"mailto:info@activevos.com\">info@activevos.com</a> to the address you provided when you registered. Activating your account will allow you to login to access all of our content.</p>";
      html += "<br />\n";
      html += "<br />\n";
      html += "<br />\n";
      html += "<br />\n";
  MyPopup.width=300;
  MyPopup.showModalWindow(html);
}

function protect_just_register_actions() {
  almost_done();
}

function protect_just_login_actions() {
//alert("protect_just_login_actions");
  $('.remote_logout').remove();
	//alert(UserAPI.cookie[i]);
  for ( var i in UserAPI.cookie ) {
    var cookie = UserAPI.cookie[i];
    for ( var j in remote_sites ) {
      $('body').append('<iframe class="remote_login" src="' + remote_sites[j] + '/login/setcookie.php?c=' + cookie + '" style="display: none"></iframe>');
    }
  }
  protect_user_actions();
  if (UserAPI.userId > 0) {
    if (clicked_id != undefined && clicked_id != null) {
      // "Кликаем" по ссылке или по плееру
      if (clicked_id.indexOf("podPressPlayerSpace") == -1) {
        // Надо кликнуть по ссылке

        $("span.protected a[rel='"+clicked_id+"']").each(function() {
          href = $(this).attr('href');
          if(href == "#") {
            var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') >  -1;
            jqObject = $(this);
            if (is_chrome && $(this).text() == "Play in Popup") {
              setTimeout("popup_link(jqObject)", 1000);
              return false;
            }
            else {
              setTimeout("jqObject.trigger('click')", 1000);
            }
          } else {
            setTimeout("openLink( href )", 1000);
			return false;
          }
        });
      }
      else {
        modifyObject( $("span.protected div[id='"+clicked_id+"'] object"), true );
      }
    }
  }
}

function popup_link(jqObject) {
  var onclick = $(jqObject).attr('onclick');
  var html  = "<span class='suc'>You've been logged in successfully!<br />";
      html += "Please, <a id=\"popup_view_link\" href=\"#\">click here</a> to open the media.</span>";
  MyPopup.showModalWindow(html);
  $('#popup_view_link').click(function () {onclick.call();MyPopup.hideModalWindow(); return false;});
}

function openLink(href) {
  //href = encodeURIComponent(href);
  //alert (href);
  //var newWin = window.open(href);
  //if (newWin != null) {
  //  newWin.focus();
  //}
  var html  = "<span class='suc'>You've been logged in successfully!<br />";
      html += "Please, <a href="+href+" target='_blank' onclick=\"MyPopup.hideModalWindow()\">click here</a> to download the file.</span>";
  MyPopup.showModalWindow(html);
  /*
  var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') >  -1;
  newwindow=window.open('', "download", "location,width=400,height=300,top=0");
  if (is_chrome) {
    newwindow.parent.blur();
  }
  newwindow.document.writeln("You've been logged in successfully.<br />");
  newwindow.document.writeln("Please, <a href="+href+" onclick="">click here</a> to download the file.");
  newwindow.focus(); 
  return false;
  */
}

function protect_just_logout_actions() {
  //delete remote cookie
  var cookie = "restoken=; Expires=Tuesday, 01-Jan-00 11:00:11 GMT; path=/";
  cookie = encodeURIComponent( cookie );
  for ( var j in remote_sites ) {
    $('body').append('<iframe class="remote_logout" src="' + remote_sites[j] + '/login/setcookie.php?c=' + cookie + '" style="display: none"></iframe>');
  }
  setTimeout("window.location.reload();", 500);
}

function protect_user_actions() {
  $('#top_links').html(logged_in_links);

  if (UserAPI.userId > 0) {
    $(".podPress_content").css("display", "block");

    // Показываем защищённое первое вложение
    //$(".first_attachment").css("display", "block");
    //$(".first_attachment").css("display", "none");
    
    // Включаем защищённый контент
    $("span.protected").css("display", "block");
    
    // Выключаем защитные заглушки
    $('.pane').remove();
    
    //Перебираем защищённые вложения.
    $("span.protected").each(function() {
      $(this).find("a").credential_add();
      $(this).find("object").each(function() {
        modifyObject($(this), false);
      });
    });
  }
}

function protect_anon_actions() {

  $('#top_links').html(anonymous_links);
  $(".podPress_content").css("display", "block");
  $('.pane').remove();

  // Чтобы тег span воспринимался как блок. Скрываем мы его ниже.
  $("span.protected").css("display", "block");
  
  //Перебираем защищённые вложения.
  $("span.protected").each(function() {
    // Читаем первую сылку.
    var link = $(this).find("a:first").attr("href");
    // удаляем credentials
    link = link.replace(/([&?]{1}u=[0-9]+)/i, "");
    link = link.replace(/([&?]{1}t=[a-f0-9]+)/i, "");
    // Выбираем расширение.
    var regexp = /\.([a-z0-9]+)[&?=a-z0-9]*$/i;
    var extension = regexp.exec(link);
    if (extension != null) {
      extension = extension[1];
    }
    $(this).find("object").each(function() {
      modifyObject($(this), false);
    });
    // Прячнм нормальные вложения
    $(this).css("display", "none");
    // В зависимости от расширения
    switch (extension) {
      case 'pdf':
        var html = pdf_pane( $(this).html() );
        $(this).after(html);
        break;
      case 'flv':
        var html = flv_pane( $(this).html() );
        $(this).after(html);
        break;
      case 'm4v':
        var html = m4v_pane( $(this).html() );
        $(this).after(html);
        break;
      case 'mp3':
        var html = mp3_pane( $(this).html() );
        $(this).after(html);
        break;
      case 'wmv':
		var html = wmv_pane( $(this).html() );
        $(this).after(html);
        break;
	  case 'avi':
		var html = avi_pane( $(this).html() );
        $(this).after(html);
        break;
      default:
    }
  });

  // Прячем защищённое первое вложение
  //$(".first_attachment").css("display", "none");
}

function pdf_pane(html) {
  if (html == undefined || html.lenght < 1) {
    return "";
  }
  html = html.replace(/onclick=['"]{0,1}[^'"]['"]{0,1}/gi, "");
  html = html.replace(/target=['"]{0,1}[^'"]['"]{0,1}/gi, "");
  html = html.replace(/href=['"]{0,1}[^'"]['"]{0,1}/gi, "href=\"javascript:void(0)\" onclick=\"javascript:onClickHyperlink(event); return false;\"");
  html = "<div class=\"pane\">" + html + "</span>";
  return html;
}

function flv_pane(html) {
  if (html == undefined || html.lenght < 1) {
    return "";
  }
  html = html.replace(/onclick="[^"]+"/gi, "");
  html = html.replace(/target="[^'"]+"/gi, "");
  html = html.replace(/href="[^'"]+"/gi, "href=\"javascript:void(0)\" onclick=\"javascript:onClickHyperlink(event); return false;\"");
  html = "<span class=\"pane\">" + html + "</span>";
  html = html.replace(/<object[\s\S]+object>/gi, "<a href=\"javascript:void(0)\" onclick=\"javascript:onClickHyperlink(event); return false;\"><img src=\"" + script_root + "login/image/video.jpg\" width=\"480\" height=\"360\" border=\"0\" /></a>");
  return html;
}

function m4v_pane(html) {
  if (html == undefined || html.lenght < 1) {
    return "";
  }
  html = html.replace(/onclick="[^"]+"/gi, "");
  html = html.replace(/target="[^'"]+"/gi, "");
  html = html.replace(/href="[^'"]+"/gi, "href=\"javascript:void(0)\" onclick=\"javascript:onClickHyperlink(event); return false;\"");
  html = "<div class=\"pane\">" + html + "</span>";
  html = html.replace(/<table[\s\S]+\/table>/gi, "<a href=\"javascript:void(0)\" onclick=\"javascript:onClickHyperlink(event); return false;\"><img src=\"" + script_root + "login/image/video.jpg\" width=\"480\" height=\"360\" border=\"0\" /></a><br />");
  return html;
}

function wmv_pane(html) {
  if (html == undefined || html.lenght < 1) {
    return "";
  }
  html = html.replace(/onclick="[^"]+"/gi, "");
  html = html.replace(/target="[^'"]+"/gi, "");
  html = html.replace(/href="[^'"]+"/gi, "href=\"javascript:void(0)\" onclick=\"javascript:onClickHyperlink(event); return false;\"");
  html = "<div class=\"pane\">" + html + "</span>";
  html = html.replace(/<table[\s\S]+\/table>/gi, "<a href=\"javascript:void(0)\" onclick=\"javascript:onClickHyperlink(event); return false;\"></a><br />");
  return html;
}

function avi_pane(html) {
  if (html == undefined || html.lenght < 1) {
    return "";
  }
  html = html.replace(/onclick="[^"]+"/gi, "");
  html = html.replace(/target="[^'"]+"/gi, "");
  html = html.replace(/href="[^'"]+"/gi, "href=\"javascript:void(0)\" onclick=\"javascript:onClickHyperlink(event); return false;\"");
  html = "<div class=\"pane\">" + html + "</span>";
  html = html.replace(/<table[\s\S]+\/table>/gi, "<a href=\"javascript:void(0)\" onclick=\"javascript:onClickHyperlink(event); return false;\"></a><br />");
  return html;
}

function mp3_pane(html) {
  if (html == undefined || html.lenght < 1) {
    return "";
  }
  html = html.replace(/<embed[^>]+>"/gi, "");
  html = html.replace(/onclick="[^"]+"/gi, "");
  html = html.replace(/target="[^'"]+"/gi, "");
  html = html.replace(/href="[^'"]+"/gi, "href=\"javascript:void(0)\" onclick=\"javascript:onClickHyperlink(event); return false;\"");
  html = "<div class=\"pane\">" + html + "</span>";
  html = html.replace(/<object[\s\S]+object>/gi, "<a href=\"javascript:void(0)\" onclick=\"javascript:onClickHyperlink(event); return false;\" class=\"mp3player\"></a>");
  return html;
}

function onClickHyperlink(event) {
  var hyperlinkElement = event.currentTarget ? event.currentTarget : event.srcElement;
  //regular link
  var rel = $(hyperlinkElement).attr('rel');
  if ( rel == undefined || rel == null || rel == "" ) {
    // link with span tag inside it
    if ( event.currentTarget == undefined ) {
      rel = $(hyperlinkElement).parent().attr('rel');
    }
    if ( rel == undefined || rel == null || rel == "" ) {
      //image
      var parent_div = null
      if (event.currentTarget == undefined) {
        parent_div = hyperlinkElement.parentElement;
      }
      else {
        parent_div = hyperlinkElement.parentNode;
      }
      rel = $(parent_div).attr("id");
      if ( rel == undefined || rel == null || rel == "" ) {
        if (event.currentTarget == undefined) {
          parent_div = hyperlinkElement.parentElement.parentElement;
        }
        else {
          parent_div = hyperlinkElement.parentNode;
        }
        rel = $(parent_div).attr("id");
      }
    }
  }
  MyPopup.width=300; 
  MyPopup.showAjaxModalWindow(script_root + "login/login.html"); 
  clicked_id = rel;
  return false;
}

function modifyObject(object, autoStart) {
  autoStart = autoStart == undefined ? false : autoStart;
  var text = object.parent().html();
  if (text == null) {
    return;
  }
  if (text.indexOf("<param ") == -1) {
    var params = "";
    object.children().each(function() {
      params += "<param value=\""+$(this).attr("value")+"\" name=\""+$(this).attr("name")+"\"/>";
    });
    text = text.replace(/<\/object>/i, params+"</object>");
  }
  if (UserAPI.userId != undefined && UserAPI.userId > 0) {
    if (text.indexOf(UserAPI.downloadToken) == -1) {
      text = text.replace(/\.(mp3|flv|pdf|mp4)/gi, ".$1%3Fu%3D"+UserAPI.userId+"%26t%3D"+UserAPI.downloadToken);
    }
  }
  text = text.replace("%2520", "%20");
  if (autoStart) {
    if (text.indexOf("autoStart=false") != -1) {
      text = text.replace(/(&|\?|&amp;)autoStart=false/gi, "");
    }
    if (text.indexOf("&autostart=no") != -1) {
      text = text.replace("autostart=no", "autostart=yes");
    }
    else if (text.indexOf("&autostart=yes") == -1) {
      text = text.replace(/(<param name="FlashVars" value="[^"]+)"/gi, "$1&autostart=yes\"");
    }
  } else {
    if (text.indexOf("autoStart=false") == -1) {
      text = text.replace(/data="([^"]+)"/mg, "data=\"$1?autoStart=false\"");
    }
    if (text.indexOf("&autostart=yes") != -1) {
      text = text.replace("&autostart=yes", "");
    }
  }
  object.parent().html(text);
}
// Add credentional data to protected links
jQuery.fn.credential_add = function() {
  return $(this).each(function() {
    var href = $(this).attr("href");
    if (href != "#" && href.indexOf(UserAPI.downloadToken) == -1) {
      href += (href.indexOf('?') + 1) ? '&' : '?';
      href += 'u=' + UserAPI.userId + '&t=' + UserAPI.downloadToken;
      $(this).attr('href', href);
    }
  });
};

// Remove credentional data from protected links
jQuery.fn.credential_remove = function() {
  return $(this).each(function(){
    var href = $(this).attr("href");
    href = href.replace(new RegExp("([&?]{1}u=[0-9]+)", "i"), "");
    href = href.replace(new RegExp("([&?]{1}t=[a-f0-9]+)", "i"), "");
    $(this).attr('href', href);
  });
};

