//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
function getPageScroll(){
  var yScroll;

  if (self.pageYOffset) {
    yScroll = self.pageYOffset;
  } else if (document.documentElement && document.documentElement.scrollTop){    // Explorer 6 Strict
    yScroll = document.documentElement.scrollTop;
  } else if (document.body) {// all other Explorers
    yScroll = document.body.scrollTop;
  }

  arrayPageScroll = new Array('',yScroll)
  return arrayPageScroll;
}

//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
  var xScroll, yScroll;

  if (window.innerHeight && window.scrollMaxY) {  
    xScroll = document.body.scrollWidth;
    yScroll = window.innerHeight + window.scrollMaxY;
  } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
    xScroll = document.body.scrollWidth;
    yScroll = document.body.scrollHeight;
  } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
    xScroll = document.body.offsetWidth;
    yScroll = document.body.offsetHeight;
  }
        
  var windowWidth, windowHeight;
  if (self.innerHeight) { // all except Explorer
    windowWidth = self.innerWidth;
    windowHeight = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
    windowWidth = document.documentElement.clientWidth;
    windowHeight = document.documentElement.clientHeight;
  } else if (document.body) { // other Explorers
    windowWidth = document.body.clientWidth;
    windowHeight = document.body.clientHeight;
  }       
        
  // for small pages with total height less then height of the viewport
  if(yScroll < windowHeight){
    pageHeight = windowHeight;
  } else { 
    pageHeight = yScroll;
  }

  // for small pages with total width less then width of the viewport
  if(xScroll < windowWidth){      
    pageWidth = windowWidth;
  } else {
    pageWidth = xScroll;
  }

  arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
  return arrayPageSize;
}



function getXMLObj(text) {
  var xmlDoc=null;
  if (window.ActiveXObject)
  {// code for IE
    xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async="false";
    xmlDoc.loadXML(text);
  }
  else if (document.implementation.createDocument)
  {// code for Mozilla, Firefox, Opera, etc.
    parser=new DOMParser();
    xmlDoc=parser.parseFromString(text,"text/xml");
  }
  return xmlDoc;
}

function log_stats() {
  var statsurl = "stats.php?";
  for (var i=0; i<arguments.length; i=i+2) {
    statsurl += arguments[i] + "=" + arguments[i+1] + "&";
  }

  var d = new Date();
  var t = d.getTime();
  statsurl += "&_t=" + t;

  $.get(statsurl, function(data) {
    // no op
  });
}

/*
 * Sends events to google analytics. If you want to send the event to stats,
 * use log_stats as well
 */
function sendEventToGA(pagename) {
  if (document.domain.indexOf("saavn.com") == -1) {return;}
  if(typeof(pageTracker) != 'undefined') {
    //find if user is logged_in, fb_logged_in or logged_out
    var status = "";
    if (isUserFBConnected() || isUserLoggedIn()) {
        if (isUserFBConnected())
            status = "fb_logged_in";
        else 
            status = "logged_in";
    }else {
        status = "logged_out";
    }
    pageTracker._setCustomVar(1, "user_logged_in_status", status,3);
    pageTracker._trackPageview("/" + pagename);
  }
}

/*
 * Use this only on the homepage. For search.php, use track_event instead.
 * This function does not rotate ads!
 */
function logAndSendEventToGA(ev) {
  log_stats('ev', ev);
  sendEventToGA(ev);
}

function log_go_to_url(ev, url, open){
    logAndSendEventToGA(ev);
    if (open=='new')
        window.setTimeout(function(){window.open(url,"_blank")}, 1000);
    else
        window.setTimeout(function(){window.open(url,"_self")},1000);
}

function is_private_listening_mode() {
  var val = getCookie('PL');
  if (val == 1) {
    return true;
  }

  return false;
}

function toggle_listening_mode() {
  setCookie('PL', 1 - getCookie('PL'));
  
  var ev = "ui:fbmusic:listeningmode:";
  if (is_private_listening_mode()) {
    ev += "private";
  } else {
    ev += "public";
  }

  logAndSendEventToGA(ev);
}

function isUserLoggedIn() {
  var username = $('span.user-name').text();
  if (username == "") {
    return false;
  }
  return true;
}

/* Returns true if the user is logged in through facebook or if 
 * the user is logged in through saavn AND connected his account with
 * facebook
 */
function isUserFBConnected() {
  if(isUserLoggedIn()) {
    var network = getCookie('network');
    if(network == 'fb' || network == 'linkedfb') {
      return true;
    }
  }
  return false;
}

function isFBUser() {
    var network = getCookie('network');
    if(network == 'fb') {
      return true;
    }
    return false;
}

function SetCookie(cookieName,cookieValue,nDays) {
  var today = new Date();
  var expire = new Date();
  if (nDays==null || nDays==0) nDays=30;
  expire.setTime(today.getTime() + 3600000*24*nDays);
  document.cookie = cookieName+"=" + escape(cookieValue) + ";expires="+expire.toGMTString() + ";path=/;domain=.saavn.com";
}

function getCookie(c_name) {
  if (document.cookie.length>0) {
    c_start=document.cookie.indexOf(c_name + "=");
    if (c_start!=-1) { 
      c_start=c_start + c_name.length+1; 
      c_end=document.cookie.indexOf(";",c_start);
      if (c_end==-1) c_end=document.cookie.length;
        return unescape(document.cookie.substring(c_start,c_end));
    } 
  }
    
  return "";
}
                                
function setLanguage(language) {
  var prev_language = getCookie('L');
  if(prev_language == '' || prev_language == null) prev_language = 'hindi';

  SetCookie('L', language, 30);
}

function getLanguage() {
  return getCookie('L');
}

var AD_TIME_CONTENT_CHANGE = 15000;
var AD_TIME_PLAYER_CHANGE = 15000;
var AD_TIME_MEDIA_CHANGE = 29000;
var AD_TIME_MEDIA_PROGRESS = 29000;
var AD_MIN_HEIGHT_FOR_STICKY = 670;
var SCREEN_SIZE_THRESHOLD = 1152;

var adrotationConfig = Array();
adrotationConfig["player:add"] = {rotate: true, minElapsedTime: AD_TIME_PLAYER_CHANGE};
adrotationConfig["player:change_position"] = {rotate: true, minElapsedTime: AD_TIME_PLAYER_CHANGE};
adrotationConfig["player:change_volume"] = {rotate: true, minElapsedTime: AD_TIME_PLAYER_CHANGE};
adrotationConfig["player:clear"] = {rotate: true, minElapsedTime: AD_TIME_PLAYER_CHANGE};
adrotationConfig["player:click_on_song"] = {rotate: true, minElapsedTime: AD_TIME_PLAYER_CHANGE};
adrotationConfig["player:click_to_pause"] = {rotate: true, minElapsedTime: AD_TIME_PLAYER_CHANGE};
adrotationConfig["player:click_to_play"] = {rotate: true, minElapsedTime: AD_TIME_PLAYER_CHANGE};
adrotationConfig["player:delete"] = {rotate: true, minElapsedTime: AD_TIME_PLAYER_CHANGE};
adrotationConfig["player:moveSong"] = {rotate: true, minElapsedTime: AD_TIME_PLAYER_CHANGE};
adrotationConfig["player:next"] = {rotate: true, minElapsedTime: AD_TIME_PLAYER_CHANGE};
adrotationConfig["player:prev"] = {rotate: true, minElapsedTime: AD_TIME_PLAYER_CHANGE};
adrotationConfig["player:repeat-set"] = {rotate: true, minElapsedTime: AD_TIME_PLAYER_CHANGE};
adrotationConfig["player:repeat-unset"] = {rotate: true, minElapsedTime: AD_TIME_PLAYER_CHANGE};
adrotationConfig["player:shuffle"] = {rotate: true, minElapsedTime: AD_TIME_PLAYER_CHANGE};
adrotationConfig["player:volume"] = {rotate: true, minElapsedTime: AD_TIME_PLAYER_CHANGE};
adrotationConfig["playlist-ajax"] = {rotate: true, minElapsedTime: AD_TIME_CONTENT_CHANGE};
adrotationConfig["playlists-ajax"] = {rotate: true, minElapsedTime: AD_TIME_CONTENT_CHANGE};
adrotationConfig["profile-ajax"] = {rotate: true, minElapsedTime: AD_TIME_CONTENT_CHANGE};
adrotationConfig["recent_songs-ajax"] = {rotate: true, minElapsedTime: AD_TIME_CONTENT_CHANGE};
adrotationConfig["search-ajax"] = {rotate: true, minElapsedTime: AD_TIME_CONTENT_CHANGE};
adrotationConfig["site:profilelist_back"] = {rotate: true, minElapsedTime: AD_TIME_CONTENT_CHANGE};
adrotationConfig["site:searchplaylist_back"] = {rotate: true, minElapsedTime: AD_TIME_CONTENT_CHANGE};
adrotationConfig["site:searchplaylist_load"] = {rotate: true, minElapsedTime: AD_TIME_CONTENT_CHANGE};
adrotationConfig["site:searchplaylist_suggestion"] = {rotate: true, minElapsedTime: AD_TIME_CONTENT_CHANGE};
adrotationConfig["player:mediaend"] = {rotate: true, minElapsedTime: AD_TIME_MEDIA_CHANGE};
adrotationConfig["player:progress"] = {rotate: true, minElapsedTime: AD_TIME_MEDIA_PROGRESS};
adrotationConfig["player:noaudioad"] = {rotate: true, minElapsedTime: 0};

var adrotationData   = Array();
adrotationData['lastRotationTime'] = getCurrentTime();
try {
  adjust_stickiness();
  alignRightContent();
}
catch (e) {}
 
function getCurrentTime() {
  var d = new Date();
  return d.getTime();
}

function rotate_searchpage_ads(eventname) {
  //console.log("trying rotate_serachapge_ads for " + eventname);
  //adjust_stickiness(eventname);

  if(companionad_showing) {
    return;
  }

  if (typeof(adrotationConfig[eventname]) != "undefined") {
    var eConfig = adrotationConfig[eventname];
    if (eConfig.rotate) {
      var currentTime = getCurrentTime();
      if (currentTime > (adrotationData['lastRotationTime'] + parseInt(eConfig.minElapsedTime))) {
        adrotationData['lastRotationTime'] = currentTime;
        document.getElementById("searchpage_adiframe").src = "/ads/searchpage_ad.php";
      }
    }
  }
}

var companionad_showing = false;
function show_companion_ad(url) {
  companionad_showing = true;
  document.getElementById("searchpage_adiframe").src = url;
}

function hide_companion_ad() {
  companionad_showing = false;
}

function hide_skin() {
  document.body.style.background = "";
  document.getElementById('bg_span').style.backgroundImage = "";
}

function is_current_skin_default() {
  var url = document.getElementById('bg_span').style.backgroundImage;
  url = url.replace(/(^url\(\"?\'?)|(\"?\'?\))/g, "");
  return url == default_skin_image_url;
}

/*function set_skin(skin_url, bg_color, show_fadein) {
  document.body.style.background = bg_color;
  skin_bg = document.getElementById('bg_span');
  skin_bg.style.backgroundImage = "url(" + skin_url  + ")";
  if((typeof show_fadein == "undefined") || (show_fadein == true)) {
    fadeIn('bg_span', 0);
  } else {
    setOpacity(skin_bg, 100);
  }
}*/

function setOpacity(obj, opacity) {
  opacity = (opacity == 100)?99.999:opacity;
  
  // IE/Win
  obj.style.filter = "alpha(opacity:"+opacity+")";
  
  // Safari<1.2, Konqueror
  obj.style.KHTMLOpacity = opacity/100;
  
  // Older Mozilla and Firefox
  obj.style.MozOpacity = opacity/100;
  
  // Safari 1.2, newer Firefox and Mozilla, CSS3
  obj.style.opacity = opacity/100;
}

function fadeIn(objId, opacity) {
  if (document.getElementById) {
    obj = document.getElementById(objId);
    if (opacity <= 100) {
      setOpacity(obj, opacity);
      opacity += 10;
      window.setTimeout("fadeIn('"+objId+"',"+opacity+")", 200);
    }
  }
}

function adjust_stickiness(eventname) {
	/*
  var rc = document.getElementById('rightcontent');
  var ad = document.getElementById('searchpage_ad');

  var sizearr = getPageSize();
  var str = "eventname = " + eventname + ", window.Height = " + sizearr[3];
  if (sizearr[3] < AD_MIN_HEIGHT_FOR_STICKY) {
    ad.className = 'searchpage_ad';
    rc.className = 'rightcontent';

    ad.style.position = 'absolute';
    ad.style.top = 420;
    ad.style.left = document.getElementById('resultlist').offsetLeft + 
		    document.getElementById('resultlist').offsetWidth + 
                    DISTANCE_BTW_RESULT_AND_RC + "px";

    rc.style.position = 'absolute';
    rc.style.top = 130;
    rc.style.left = document.getElementById('resultlist').offsetLeft + 
		    document.getElementById('resultlist').offsetWidth + 
                    DISTANCE_BTW_RESULT_AND_RC + "px";
  }
  else {
    ad.className = 'searchpage_ad_fixed';
    rc.className = 'rightcontent_fixed';

    ad.style.position = (navigator.appName=='Microsoft Internet Explorer')? 'absolute' : 'fixed';
    ad.style.top = (document.compatMode && document.compatMode=='CSS1Compat')? documentElement.scrollTop+420: document.body.scrollTop+420;

    rc.style.position = (navigator.appName=='Microsoft Internet Explorer')? 'absolute' : 'fixed';
    rc.style.top = (document.compatMode && document.compatMode=='CSS1Compat')? documentElement.scrollTop+130: document.body.scrollTop+130;
  }
*/

}

function show() {
  for (var i = 0; i < arguments.length; i++) {
    var node = document.getElementById(arguments[i]);
    if(node == null) continue;
    node.className = node.className.replace('hidden', 'visible');
  }
}

function hide() {
  for (var i = 0; i < arguments.length; i++) {
    var node = document.getElementById(arguments[i]);
    if(node == null) continue;
    if(node.className == '') {
      node.className = 'hidden';
    } else {
      node.className = node.className.replace('visible', 'hidden');
    }
  }
}

function toggle_show() {
  for (var i = 0; i < arguments.length; i++) {
    var node = document.getElementById(arguments[i]);
    if(node == null) continue;
    if(node.className.search('visible') != -1) {
      node.className = node.className.replace('visible', 'hidden');
    } else {
      node.className = node.className.replace('hidden', 'visible');
    }
  }  
}

function show_message(elementid, msg) {
  var node = document.getElementById(elementid);
  node.innerHTML = msg;
  node.className = node.className.replace('hidden', 'visible');
}

function hide_message(elementid) {
  var node = document.getElementById(elementid);
  node.className = node.className.replace('visible', 'hidden');
}

function log_in_console(s) {
  if (typeof console != "undefined") {
    console.log(s);
  }
}

