// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

function showBlurLayer() {
    var blurLayer = $("divBlurLayer");
    blurLayer.style.width = document.body.scrollWidth + "px";
    blurLayer.style.height = document.body.scrollHeight + "px";
    blurLayer.parentNode.removeChild(blurLayer);
    blurLayer.setOpacity(0.9)
    document.body.appendChild(blurLayer);
    blurLayer.show();
}

function getWidth()
{
  if (document.body.clientWidth > document.viewport.getWidth())
  {
    return document.body.clientWidth;
  }
  else
  {
    return document.viewport.getWidth();
  }
}

function getHeight()
{
  if (document.body.clientHeight > document.viewport.getHeight())
  {
    return document.body.clientHeight;
  }
  else
  {
    return document.viewport.getHeight();
  }
}


toggle_edit_rule = function(id) {
    $('show_ivr_node_rule_' + id).toggle();
    $('edit_ivr_node_rule_' + id).toggle();
};

toggle_edit_input_handler = function(id) {
    $('show_ivr_no_match_prompt_' + id).toggle();
    $('edit_ivr_no_match_prompt_' + id).toggle();
};

toggle_edit_silence_handler = function(id) {
    $('show_ivr_no_input_prompt_' + id).toggle();
    $('edit_ivr_no_input_prompt_' + id).toggle();
};

function toggle_default_text(toggle, text_box_id, default_text) {
    var text_box_text = $(text_box_id).value;
    if (text_box_text == default_text && toggle == 'hide') {
        $(text_box_id).writeAttribute("value", "");
    }
    ;
    if (text_box_text == "" && toggle == 'show') {
        $(text_box_id).writeAttribute("value", default_text);
    }
    ;
    return false;
}
;

function toggle_check_boxes(selector, value)
{
    $$(selector).each(function(cb) {
        cb.checked = value;
    });
}
;

function ApproveAllUnflagged() {
    var agree = confirm('Are you sure you want to approve all unflagged transfers?');
    if (agree) {
        $('approve').submit();
    }
    ;
}
;


document.observe("dom:loaded", function() {
    // do ajax pagination for list of favorites on my account page
    //var faves = $('account_favorites');
    //if(faves) {
    //  faves.observe('click', function(e) {
    //    var el = e.element();
    //    console.log(el.href);
    //    if (el.match('.pagination a')) {
    //      new Ajax.Updater('account_favorites', el.href, { method: 'get' });
    //      e.stop();
    //    }
    //  });
    //}
    try { // quick IE6 fix for $$("a[data-listing-click]")
        attachClickthroughTracking($$("a.listing-click"));
    } catch (e) {
    }
});

function redirectTo(href) {
    document.location = href;
}

function attachClickthroughTracking(linksWithClickthroughs) {
    for (var i = 0; i < linksWithClickthroughs.length; ++i) {
        linksWithClickthroughs[i].observe("click", function(event) {
            this.stopObserving('click');
            var href = this.href;
            var click_impression = this.readAttribute("data-listing-click").split(',');
            var timeout = setTimeout(function() {
                redirectTo(href)
            }, 2000);
            new Ajax.Request("/click_impressions", {
                parameters: {
                    "click_impression[listing_id]": click_impression[0],
                    "click_impression[context]": click_impression[1],
                    "click_impression[listing_index]": click_impression[2]
                },
                onComplete: function(transport) {
                    clearTimeout(timeout);
                    redirectTo(href);
                }
            });
            Event.stop(event);
        });
    }
}

function setTextContent(element, text) {
    while (element.firstChild !== null)
        element.removeChild(element.firstChild); // remove all existing content
    element.appendChild(document.createTextNode(text));
}


function displayFlash(message, flashType) {
    if (typeof(flashType) == "undefined") {
        flashType = "notice";
    }
    $("flash_container").innerHTML = "<div class='" + flashType + "'></div>";
    setTextContent($("flash_container").select("." + flashType)[0], message);
}
function copyDescription(from,to){
  $(to).value = $(from).value
  $('sanitized_error').hide()
}
function callWindowPreview(from,to){
	window.open('','mywindow_preview','menubar=1,resizable=1,scrollbars=1,width=1024,height=768');
	$(to).value = $(from).value
	$('form_sanitized').submit()
}

function alert_error_message(error,bool_alert){
  if (bool_alert){
  alert(error);
  return false
  }
}
function HideDIV(d) { document.getElementById(d).style.display = "none"; }
function DisplayDIV(d) { document.getElementById(d).style.display = "block"; }

function fix_lightbox_positions() {
	if($$('.lightbox_container')) {
	  margin = "-" + [(document.viewport.getDimensions().height / 2) - 20, ($$('.lightbox_container').first().getHeight() / 2)].min() + "px";
	  $$('.lightbox_container').first().setStyle({marginTop: margin});
	  $$('.lightbox_container').first().style.marginTop = margin;
	}
}

function header_remote_submit(form) {
  new Ajax.Request($(form).readAttribute('action'), {
    method: 'post',
    parameters: $(form).serialize() + "&format=js",
    onComplete: function(response) {
      var json = response.responseText.evalJSON(),
          flashType = json.flash_type,
          message = json.message;

      if (typeof(flashType) == "undefined")
        flashType = "notice";

      $("flash_container").update("<div class='" + flashType + "'>" + message + "</div>");
    }
  });
}

// if we're on pages:
//  /account
//  /account/my_listings
function isAccountPage() {
  return (/\/account$/.test(window.location) || /\/account\/my_listings$/.test(window.location))
}

$(document).observe("dom:loaded", function(){


  /*********** HEADER ***********/
  var obj = $$("#userMenu small")[0],
      menu = $("userMenu"),
      body = $$("body")[0];
  if (obj) {
    if(navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/iPad/i)) {
      obj.observe("click", function(){
        if (menu.hasClassName("now"))
          menu.removeClassName("now");
        else
          menu.addClassName("now");
      });
    } else {
      obj.observe("mouseover", function(){
        menu.addClassName("now");
      });

      body.observe("mouseover", function(e){
        var el = Event.findElement(e, '#userMenu');
        if (menu.hasClassName("now") && el != menu)
          menu.removeClassName("now");
      });
    }
  }

  if ($('advisor_header_form')) {
    $('advisor_header_form').observe('submit', function(e) {
      if(!isAccountPage()) {
        Event.stop(e);
        header_remote_submit('advisor_header_form');
      }
    });

    $('current_advisor_status').observe('change', function(e) { isAccountPage() ? $('advisor_header_form').submit() : header_remote_submit('advisor_header_form'); });

    if($('default_phone')) {
		$('default_phone').observe('change', function(e) { isAccountPage() ? $('advisor_header_form').submit() : header_remote_submit('advisor_header_form'); });
	}
  }

  if ($('call_me_at_form')) {
    $('call_me_at_form').observe('submit', function(e) {
      if(!isAccountPage()) {
        Event.stop(e);
        header_remote_submit('call_me_at_form');
      }
    });

    $('default_phone').observe('change', function(e) { isAccountPage() ? $('call_me_at_form').submit() : header_remote_submit('call_me_at_form'); });
  }

  if ($('btn-search-icon'))
    $('btn-search-icon').observe('click', function(e) { $('global_search_form').submit(); });

  var autocompleteObject = JQ("#searchinput").autocomplete({
    minLength:1,
      source:function (request, response) {
        JQ.ajax({
          url:searchHost + "/search/suggestions?wt=json",
          dataType:"jsonp",
          jsonp:'json.wrf',
          data:{
            q:request.term,
            indent:"off",
            category:839
          },
          success:function (data) {
            beginListings = 0;
            beginUsers = 0;
            beginCategories = 0;
            response(JQ.map(data.response.docs, function (item) {
              return item;
            }));
          }});
        },
        open:function () {
          JQ(this).removeClass("ui-corner-all").addClass("ui-corner-top");
        },
        close:function () {
          JQ(this).removeClass("ui-corner-top").addClass("ui-corner-all");
        },
        select:function (event, ui) {
          if (ui.item.listing_id)
            window.open(location.protocol + '//' + location.host + "/listings/show/" + ui.item.listing_id, "_self", false);
          if (ui.item.user_id)
            window.open(location.protocol + '//' + location.host + "/users/show/" + ui.item.user_id, "_self", false);
          if (ui.item.category_id)
            window.open(location.protocol + '//' + location.host + "/categories/" + ui.item.category_id, "_self", false);
          if (ui.item.count)
            window.open(location.protocol + '//' + location.host + "/search?text=" + ui.item.query, "_self", false);
        }
    }).data("autocomplete");

    if (autocompleteObject) {
      autocompleteObject._renderItem = function (ul, item) {
        if (item.title) {
          var pitch = item.category_path;
          if (pitch.length > 60)
            pitch = item.category_path.substr(0, 60) + "...";

          var title = item.title;
          if (title.length > 30)
            title = item.title.substr(0, 30) + "...";

          if (beginListings == 0) {
            beginListings = 1;
            if (item.photo_file_name) {
              return JQ("<li></li>")
                .data("item.autocomplete", item)
                .append("<div id=\"searchHeader\">&nbsp;Listings</div><a><div id=\"searchRes\"><div class=\"searchResPhoto\">" +
                "<img src=\"" + item.photo_file_name + "\" onerror=\"this.src='../../images/placeholder.gif'\" border=\"0\"></div>" +
                "<div class=\"searchResText\"><strong>" + title + "</strong><br>" + pitch + "<br class=\"clear\"></div></div></a>")
                .appendTo(ul);
            } else {
              return JQ("<li></li>")
                .data("item.autocomplete", item)
                .append("<div id=\"searchHeader\">&nbsp;Listings</div><a><div id=\"searchRes\"><div class=\"searchResPhoto\">" +
                "<img src=\"" + item.photo_file_name + "\" onerror=\"this.src='../../images/blank.png'\" border=\"0\"></div>" +
                "<div class=\"searchResText\"><strong>" + title + "</strong><br>" + pitch + "<br class=\"clear\"></div></div></a>")
                .appendTo(ul);
            }
          } else {
              if (item.photo_file_name) {
                return JQ("<li></li>")
                  .data("item.autocomplete", item)
                  .append("<a><div id=\"searchRes\"><div class=\"searchResPhoto\">" +
                  "<img src=\"" + item.photo_file_name + "\" onerror=\"this.src='../../images/placeholder.gif'\" border=\"0\">" +
                  "</div><div class=\"searchResText\"><strong>" + title + "</strong><br>" + pitch +
                  "<br class=\"clear\"></div></div></a>")
                  .appendTo(ul);
              } else {
                return JQ("<li></li>")
                  .data("item.autocomplete", item)
                  .append("<a><div id=\"searchRes\"><div class=\"searchResPhoto\">" +
                  "<img src=\"" + item.photo_file_name + "\" onerror=\"this.src='../../images/blank.png'\" border=\"0\">" +
                  "</div><div class=\"searchResText\"><strong>" + title + "</strong><br>" + pitch +
                  "<br class=\"clear\"></div></div></a>")
                  .appendTo(ul);
              }
            }
        }
        if (item.login) {
          var firstname = item.first_name;
          if (!firstname)
            firstname = "";

          var lastname = item.last_name;
          if (!lastname)
            lastname = "";

            if (beginUsers == 0) {
              beginUsers = 1;
              if (item.photo_file_name) {
                return JQ("<li></li>")
                  .data("item.autocomplete", item)
                  .append("<div id=\"searchHeader\">&nbsp;Flirts</div><a><div id=\"searchRes\"><div class=\"searchResPhoto\">" +
                  "<img src=\"" + item.photo_file_name + "\" onerror=\"this.src='../../images/placeholder.gif'\" border=\"0\">" +
                  "</div><div class=\"searchResText\"><strong>" + item.login + "</strong><br>" + firstname + " " + lastname +
                  "<br class=\"clear\"></div></div></a>")
                  .appendTo(ul);
              } else {
                return JQ("<li></li>")
                  .data("item.autocomplete", item)
                  .append("<div id=\"searchHeader\">&nbsp;Flirts</div><a><div id=\"searchRes\"><div class=\"searchResPhoto\">" +
                  "<img src=\"" + item.photo_file_name + "\" onerror=\"this.src='../../images/blank.png'\" border=\"0\"></div>" +
                  "<div class=\"searchResText\"><strong>" + item.login + "</strong><br>" + firstname + " " + lastname +
                  "<br class=\"clear\"></div></div></a>")
                  .appendTo(ul);
              }
            } else {
              if (item.photo_file_name) {
                return JQ("<li></li>")
                  .data("item.autocomplete", item)
                  .append("<a><div id=\"searchRes\"><div class=\"searchResPhoto\">" +
                  "<img src=\"" + item.photo_file_name + "\" onerror=\"this.src='../../images/placeholder.gif'\" border=\"0\">" +
                  "</div><div class=\"searchResText\"><strong>" + item.login + "</strong><br>" + firstname + " " + lastname +
                  "<br class=\"clear\"></div></div></a>")
                  .appendTo(ul);
              } else {
                  return JQ("<li></li>")
                    .data("item.autocomplete", item)
                    .append("<a><div id=\"searchRes\"><div class=\"searchResPhoto\">" +
                    "<img src=\"" + item.photo_file_name + "\" onerror=\"this.src='../../images/blank.png'\" border=\"0\"></div>" +
                    "<div class=\"searchResText\"><strong>" + item.login + "</strong><br>" + firstname + " " + lastname +
                    "<br class=\"clear\"></div></div></a>")
                    .appendTo(ul);
              }
            }
        }

        if (item.category_path) {
          if (beginCategories == 0) {
            beginCategories = 1;
            return JQ("<li></li>")
              .data("item.autocomplete", item)
              .append("<div id=\"searchHeader\">&nbsp;Categories</div><a><div id=\"searchResCat\">" + item.category_path + "</div></a>")
              .appendTo(ul);
          } else {
            return JQ("<li></li>")
              .data("item.autocomplete", item)
              .append("<a><div id=\"searchResCat\">" + item.category_path + "</div></a>")
              .appendTo(ul);
            }
        }

        if (item.count && item.count > 0) {
          return JQ("<li></li>")
            .data("item.autocomplete", item)
            .append("<a><div id=\"searchMoreResults\"><strong>See more results for " + item.query +
            " </strong><br>Displaying top " + item.count + " results</div></a>")
            .appendTo(ul);
        }
      };
    }
});

