var _1on1 = {
  listing: "/1on1/ajax_listing/",
  active: "/1on1/ajax_active/",
  online: "/media/images/design/1on1/greendot.png", //25x25
  offline: "/media/images/design/1on1/reddot.png",
  spy: "/media/images/design/1on1/voyeur_overlay.png", //160x120
  onBreak: "/media/images/design/1on1/break_overlay.png",
  blank: "/media/images/design/spacer.gif",
  no_image: "/media/images/design/1on1/no_image.jpg",
  appUrl: "/1on1/",
  timer: null,
  defaultTime: 60000, 
  models: null,
  preset: "performer_",
  ignore: "test performer",
  freeChat: "Start Free Chat",
  changeDetected: false,
  lastActiveCount: 0,
  enableChangeDetection: true, //set to true to cut down on calls to server
  justLoaded: true, //if 1st time loading and changed detected, no need to pull up listing immediately
  rpp: 50,
  ids: null,
  page: 1,
  totalRecords: 0,
  allowHeight: true,
  mpa3: ""
};

init1on1 = function(mpa3) {
  //only load if page has correct container
  if (document.getElementById("div_1on1")) {
    _1on1.models = new Array();

    sizeDiv();
    //sometimes height is not set correctly, so try again
    setTimeout("sizeDiv()", 1500);

    //bind navigation buttons
    $("#prevPage").click(function(e) {
        e.preventDefault();
        previousPage();
    });

    $("#nxtPage").click(function(e) {
        e.preventDefault();
        nextPage();
    });

    if (mpa3 != undefined && mpa3 != "") {
        _1on1.mpa3 = "mpa3=" + mpa3;
    }

    getModels();
  }
}

sizeDiv = function() {
    //try to set the height of the container to match the content area's height on each page
    if (_1on1.allowHeight) {
        var docHgt = (document.getElementById("mainbox") != undefined) ? document.getElementById("mainbox").offsetHeight : 0;
        if (docHgt == 0 || docHgt < 300) docHgt = 820;
        var offset = 100;

        $("#div_1on1").css("height", (docHgt-offset) + "px");
    }    
}

modelExists = function(id) {
  return (_1on1.models[id] != undefined);
}

/*
* get the list of models, which has the sort order
*/
getModels = function() {
  _1on1.ids = new Array();

  $.ajax({
     url: _1on1.listing,
     type: "GET",
     dataType: "json",
     success: function(response) {
         parseModels(response);
     },
     error: function() {
         //console.log("err in getmodels");
     }
  });
}

/*
* parses the model listing data. on first load changeDeteted is false, so getActive is called
  otherwise timer is set to call getActive since getActive would've called getModels on a changeDetected
*/

var temp = new Array();
parseModels = function(data) {
  try {
    var obj = data;//jQuery.parseJSON(data);
    var len = obj.performers.length;
    var item = null;
    var name = "";
    var count = 0; //accurate length since we ignore certain ones

    for (var i = 0; i < len; i++) {
      item = obj.performers[i];
      name = item.stage_name;
      if (name.toLowerCase().indexOf(_1on1.ignore) == -1) {
        createModel(item.id, name, item.photo, item.status);
        count++;
      }
    }
    
    _1on1.totalRecords = count;

    getPage(_1on1.page);

    if (_1on1.enableChangeDetection) {
      if (_1on1.changeDetected) {
        _1on1.changeDetected = false;
        //_1on1.timer = 
        setTimeout("getActive()", _1on1.defaultTime);
      }
      else {
        getActive();  
      }
    }
    else {
      getActive();
    }

  } catch (err) {
    //alert('err: '+  err);
    console.log("parsemodels: " + err);
  }  
}

/*
* get active models
*/
getActive = function() {
  $.ajax({
     url: _1on1.active,
     type: "GET",
     dataType: "json",
     success: function(response) {
         parseActive(response);
     },
     error: function() {
      //console.log("err in getactive");
     }
  });
}

/*
* parse active models info and update model listing
*/
parseActive = function(data) {
  try {
    var obj = data;//jQuery.parseJSON(data);
    var len = obj.streams.length;
    var item = null;
    var name = "";

    log("checking " + _1on1.lastActiveCount +",  " + len);
    if (!_1on1.changeDetected && _1on1.lastActiveCount != len) {
      _1on1.changeDetected = true;
      log("changeDetected in count (in parseActive)");
    }

    for (var i = 0; i < len; i++) {
      item = obj.streams[i];
      name = item.performer_name;
      if (name.toLowerCase().indexOf(_1on1.ignore) == -1) { 
        updateModel(item.performer_id, item.performer_status, item.current_performance_type, item.id, item.shows[0].rate, false);
      }
    }

    _1on1.lastActiveCount = len;

    //if change was detected by updateModels, then need to reload the models listing for sort order
    //otherwise load active next time
    if (_1on1.enableChangeDetection) {
      if (_1on1.changeDetected && !_1on1.justLoaded) {
        log("changeddetected is true. getModels()");
        getModels();
      }
      else {
        log("settimer for getactive");
        //_1on1.timer = 
        setTimeout("getActive()", _1on1.defaultTime);
      }
    }
    else {
      setTimeout("getModels()", _1on1.defaultTime);
    }

    if (_1on1.justLoaded) {
      _1on1.justLoaded = false;
    }   

  } catch (err) {
    console.log(err);
  }
}

enterRoom = function(room, privateR, performer_id) {
  if (room != undefined && room != 0) {
      //var url = _1on1.appUrl + "?stream=" + room + "&private=" + privateR;
      var url = _1on1.appUrl + room + "/" + performer_id + "/" + privateR;
      if (_1on1.mpa3 != "") url += "?" + _1on1.mpa3;
      document.location.href = url;
  }  
}

/*
* creates a container for a model listing his name, img, show type, and button
* if the model doesn't exist he is added otherwise we update his info the (updateModel method).
* New models get added to the main 1on1 container.
*/
createModel = function(id, name, photo, status) {  
  //for paging
  _1on1.ids.push(id);

  if (modelExists(id)) {
    //if a model went offline this is how we update that info
    updateModel(id, status, "", 0, -1, true);
  }
  else {
    var shortName = (name.length > 14) ? name.substring(0, 14) + "..." : name;
    if (status == "logged_in") status = "offline";

    //the pure document.createElement seems to be faster than going thru JQuery
    var div = document.createElement('DIV');
  	div.className = "div_1on1_model";
  	div.id = _1on1.preset + id;
  	//div.setAttribute("style", "display:none"); //hide until paginated

  	//create the header which is the on/off img + performer name
  	var header = document.createElement('DIV');
  	header.className = "header";

  	//on/off img
  	var img = document.createElement('IMG');
  	img.className = "image";
  	img.id = _1on1.preset + "icon_" + id;
  	img.src = (status == "offline") ? _1on1.offline : _1on1.online;

  	//performer name
  	var title = document.createElement('DIV');
  	title.className = "title";
  	title.innerHTML = shortName;
  	title.title = name;

    //add img + title to header
  	header.appendChild(img);
  	header.appendChild(title);

  	//add header to container
  	div.appendChild(header);

  	//create the body which is the image container (model image + overlay)
  	var imgContainer = document.createElement('DIV');
  	imgContainer.className = "image_container";

  	//model image
  	img = document.createElement('IMG');
  	img.className = "model_image";
  	img.src = (photo != null) ? photo : _1on1.no_image;

    //a href
    var ahref = document.createElement('A');
    ahref.id = _1on1.preset + "href_" + id;
    var url = _1on1.appUrl + "0/" + id + "/0";
    if (_1on1.mpa3 != "") {
        url += "?" + _1on1.mpa3;
    }
    ahref.href = url;
    ahref.appendChild(img);

  	//add model img to img container
  	//imgContainer.appendChild(img);
    imgContainer.appendChild(ahref);

  	//overlay over image
  	img = document.createElement('IMG');
  	img.className = "overlay";
  	img.id = _1on1.preset + "overlay_" + id;

    //set correct overlay image based on status
  	if (status == "break") {
  	  img.src = _1on1.onBreak;
  	}
  	else if (status == "in_private") {
  	    img.src = _1on1.spy;
  	}
  	else {
  	  img.src = _1on1.blank;
	  }

    //add overlay to img container
  	imgContainer.appendChild(img);

  	//add imgContainer
  	div.appendChild(imgContainer);

  	//create the footer which is the Show: xxxxxxx
  	title = document.createElement('DIV');
  	title.className = "show";
  	title.innerHTML = "Show: ";

    //add the text 'Show: '
  	div.appendChild(title);

    //show type
  	title = document.createElement('DIV');
  	title.className = "show_type";
  	title.id = _1on1.preset + "showtype_" + id;
  	
  	ahref = document.createElement('A');
    ahref.id = _1on1.preset + "href2_" + id;
    var url = _1on1.appUrl + "0/" + id + "/0";
    if (_1on1.mpa3 != "") {
        url += "?" + _1on1.mpa3;
    }
    ahref.href = url;
    ahref.innerHTML = "View My Page";
    title.appendChild(ahref);
  	//title.innerHTML = "View My Page";

    //add the show type
  	div.appendChild(title);

  	//create the button area which is the button container to hold the button.
  	//the button changes based on status
  	var buttonContainer = document.createElement('DIV');
  	buttonContainer.className = "button_container";

  	var button = document.createElement('INPUT');
  	button.id = _1on1.preset + "button_" + id;
  	button.className = "button";
  	button.type = "button";
  	button.value = "";//_1on1.freeChat;
  	button.setAttribute("style", "display:none"); 

  	switch (status) {
	    case "streaming":
	    case "break":
	      button.className = "button yellow";    
	      break;
      case "in_private":
        button.className = "button green"; 
        break;
	  }

	  buttonContainer.appendChild(button);

	  div.appendChild(buttonContainer);

	  //add the model to the container
    $("#div_1on1").append(div);

    //for quick look up of existing model
    _1on1.models[id] = { status: status, room: 0 };

  } 
}

/*
* updates an existing model to reflect changes in his chatroom status
  id = used to find the div
  status = performers status, used to update several items
  spyRate = for the 'spy' button to display the voyeur rate
  move = if the div needs to be repositioned (sort order). true when called by parseModels, false for parseActive
*/
updateModel = function(id, status, showType, showId, spyRate, move) {
  if (!move) {
    //if no changeDetected yet let's see if this current set has changed
    if (_1on1.enableChangeDetection) {

      if (!_1on1.changeDetected) {      
          //see if there was a possible change in active models. 
          //if we detected at least one change then no need to keep looking
          if (modelExists(id)) {
            if (!_1on1.changeDetected && _1on1.models[id]['status'] != status) {
              _1on1.changeDetected = true;
              //log("changeDetected in status for " + id + ", old: " + _1on1.models[id]['status'] + ", new: " + status);
            }

            if (!_1on1.changeDetected && _1on1.models[id].room != showId) {
              _1on1.changeDetected = true;
              //log("changeDetected in room id");
            }  
          }
      }
    }

    _1on1.models[id] = { status: status, room: showId };
  }

  switch (status) {
      case "in_private":
        $("#" + _1on1.preset + "icon_" + id).attr("src", _1on1.online);
        $("#" + _1on1.preset + "overlay_" + id).attr("src", _1on1.spy);
        if (showType != "") $("#" + _1on1.preset + "showtype_" + id).html(showType);
        $("#" + _1on1.preset + "button_" + id).removeClass();
        $("#" + _1on1.preset + "button_" + id).addClass("button green");
        if (spyRate != -1) $("#" + _1on1.preset + "button_" + id).val("Spy for " + spyRate + " credits/min");
        if (showId != 0) {
          $("#" + _1on1.preset + "button_" + id).data({ 'room': showId, 'private': 1, 'performer_id': id });
        }  
        $("#" + _1on1.preset + "button_" + id).unbind("click");
        $("#" + _1on1.preset + "button_" + id).click(function() {
            enterRoom($(this).data('room'), $(this).data('private'), $(this).data('performer_id'));
          });
        $("#" + _1on1.preset + "button_" + id).show();
        $("#" + _1on1.preset + "href_" + id).attr("href", _1on1.appUrl + showId + "/" + id + "/1" + ((_1on1.mpa3 != "") ? "?" + _1on1.mpa3 : ""));
        break;

      case "streaming":
        $("#" + _1on1.preset + "icon_" + id).attr("src", _1on1.online);
        $("#" + _1on1.preset + "overlay_" + id).attr("src", _1on1.blank);
        if (showType != "") $("#" + _1on1.preset + "showtype_" + id).html(showType);
        $("#" + _1on1.preset + "button_" + id).removeClass();
        $("#" + _1on1.preset + "button_" + id).addClass("button yellow");
        $("#" + _1on1.preset + "button_" + id).val(_1on1.freeChat);
        if (showId != 0) {
          $("#" + _1on1.preset + "button_" + id).data({ 'room': showId, 'private': 0, 'performer_id': id });
        }  
        $("#" + _1on1.preset + "button_" + id).unbind("click");
        $("#" + _1on1.preset + "button_" + id).click(function() {
            enterRoom($(this).data('room'), $(this).data('private'), $(this).data('performer_id'));
          });
        $("#" + _1on1.preset + "button_" + id).show();
        $("#" + _1on1.preset + "href_" + id).attr("href", _1on1.appUrl + showId + "/" + id + "/0" + ((_1on1.mpa3 != "") ? "?" + _1on1.mpa3 : ""));
        break;

      case "break":
        $("#" + _1on1.preset + "icon_" + id).attr("src", _1on1.online);
        $("#" + _1on1.preset + "overlay_" + id).attr("src", _1on1.onBreak);
        if (showType != "") $("#" + _1on1.preset + "showtype_" + id).html(showType);
        $("#" + _1on1.preset + "button_" + id).removeClass();
        $("#" + _1on1.preset + "button_" + id).addClass("button yellow");
        $("#" + _1on1.preset + "button_" + id).val(_1on1.freeChat);
        if (showId != 0) {
          $("#" + _1on1.preset + "button_" + id).data({ 'room': showId, 'private': 0, 'performer_id': id });
        } 
        $("#" + _1on1.preset + "button_" + id).unbind("click");
        $("#" + _1on1.preset + "button_" + id).click(function() {
            enterRoom($(this).data('room'), $(this).data('private'), $(this).data('performer_id'));
          });
        $("#" + _1on1.preset + "button_" + id).show();
                $("#" + _1on1.preset + "href_" + id).attr("href", _1on1.appUrl + showId + "/" + id + "/0" + ((_1on1.mpa3 != "") ? "?" + _1on1.mpa3 : ""));
        break;

      case "offline":
      default:
        $("#" + _1on1.preset + "icon_" + id).attr("src", _1on1.offline);
        $("#" + _1on1.preset + "overlay_" + id).attr("src", _1on1.blank);
        $("#" + _1on1.preset + "href2_" + id).attr("href", _1on1.appUrl + "0/" + id + "/0" + ((_1on1.mpa3 != "") ? "?" + _1on1.mpa3 : ""));
        $("#" + _1on1.preset + "showtype_" + id).html("View My Page");
        $("#" + _1on1.preset + "button_" + id).hide();
        $("#" + _1on1.preset + "button_" + id).unbind("click");
        $("#" + _1on1.preset + "href_" + id).attr("href", _1on1.appUrl + "0/" + id + "/1" + ((_1on1.mpa3 != "") ? "?" + _1on1.mpa3 : ""));
        break;
  }

  if (move) {
    //remove from position
    var div = $("#" + _1on1.preset + id).detach();

    //and add back to the beginning
    $("#div_1on1").append(div);
  }  
}

/* gets a 'page' */
getPage = function(page) {
  if (page == 0) page = 1;
  var lastPage = Math.ceil(_1on1.totalRecords / _1on1.rpp);
  var offset = (page - 1) * _1on1.rpp;
  var len = ( (offset + _1on1.rpp) > _1on1.totalRecords) ? _1on1.totalRecords : (offset + _1on1.rpp) ;
  var id;

  (page != 1) ? $("#prevPage").show() :$("#prevPage").hide();
  (page < lastPage) ? $("#nxtPage").show() : $("#nxtPage").hide();

  if (lastPage > 1) {
    $("#pageInfo").html("Page " + page + " of " + lastPage);
  }
  else {
    $("#pageInfo").html("");
  }

  //need to hide/show correct ones
  for(var i = 0; i < _1on1.totalRecords; i++) {
    id = _1on1.ids[i];
    if (i >= offset && i < len) {
      $("#" + _1on1.preset + id).show();
    }
    else {
      if ($("#" + _1on1.preset + id).css("display") == "block") {
        $("#" + _1on1.preset + id).hide();
      }
    }
  } 
}

previousPage = function() {
  if (_1on1.page > 1) {
     _1on1.page--;
     getPage(_1on1.page);
  }
}

nextPage = function() {
  var lastPage = Math.ceil(_1on1.totalRecords / _1on1.rpp);
  if (_1on1.page < lastPage) {
    _1on1.page++;
    getPage(_1on1.page);
  }
}

log = function(txt) {
  ;//$("#debug").html( $("#debug").html() + "\n" + txt);
}
