/**
 * forum/detail.js
 * Functions for posts in a thread
 * Functions beginning with an underscore are internal and should not be called by an event listener
 *
 * Dependencies
 * - YUI
 *
 * @author Karen <kziv@gaiaonline.com>
 **/

(function($){
	$.namespace('GAIA_FLASH');
	GAIA_FLASH.callToFlashObjects = function (fn, args) {
		$('.forum-flash-sigs').each(function(){
			if ($.isIE) // bad IE
				window[this.id][fn](args); 

			else { // w3c compliant browsers
				if (this[fn])
					this[fn](args); // either embed or object
			}
		});
			
	};
})(YAHOO.util.Short);


var DOM = YAHOO.util.Dom;
var Event = YAHOO.util.Event;
var qr = {
  open: false,
  show_captcha: false,
  initted: false,
  nonce: null,
  post_url: null,
  nonce_url: null,
  captcha: {challenge: null, url: null},
  posting: false,
  pageName: null
};

YAHOO.namespace('gaia.app.Forum');
YAHOO.gaia.app.Forum.Detail = function() {

    // Deleted post show/hide
    var show_deleted_triggers = DOM.getElementsByClassName('post-show');
    Event.addListener(show_deleted_triggers, 'click', this.showPost, this);

    // Inventory toggle
    var items = DOM.getElementsByClassName('itemDisplay');
    Event.addListener(items, 'click', this.toggleItemDetails);

    items = DOM.getElementsByClassName('quick_reply');
    Event.addListener(items, 'click', this.toggleQuickReply, this);

    // Gigya widget toggle
    YAHOO.namespace("gigya");

    // set up the panel widget
    YAHOO.gigya.panel = new YAHOO.widget.Panel("gigya_widget", {
		width:"106px",
        height: "260px",
        visible:false,
        draggable:false,
        constraintoviewport:true,
        context:['gigya-trigger','tr','br'],
        close: false
	});
    // render the panel
    YAHOO.gigya.panel.render();

    // when you click on the 'Share:' link, it will activate the panel or hide it
    YAHOO.util.Event.addListener("gigya-trigger", 'click', function() { ( ! YAHOO.gigya.panel.cfg.getProperty("visible") ) ? YAHOO.gigya.panel.show() : YAHOO.gigya.panel.hide();return false; }, this);

    // when showing the panel, initialize the gigya widget
    YAHOO.gigya.panel.showEvent.subscribe(function(){ 

            gigyatitle = document.title.split("|");

        Wildfire.initPost('gaiaonline','divWildfirePost', 106, 260, {   
                    defaultContent : "gigya-content", // Default was postContent
                    useFacebookMystuff: 'false', 
                    widgetTitle: gigyatitle[0],
                    contentIsLayout: 'false', 
                    UIConfig: '<config baseTheme="v2"><display showEmail="false" showPost="false" showBookmark="false" showCodeBox="false" networksToShow="facebook, twitter, myspace, digg, delicious, bebo, blogger"></display><body><background gradient-color-begin="#FFFFFF" gradient-color-end="#FFFFFF" corner-roundness="0;0;0;0"></background><controls><snbuttons type="Standard" frame-color="#FFFFFF" background-color="#FFFFFF" over-frame-color="#FFFFFF" over-background-color="#FFFFFF" gradient-color-end="#FFFFFF" size="11" down-frame-color="#FFFFFF" down-gradient-color-begin="#FFFFFF" over-gradient-color-end="#FFFFFF" down-gradient-color-end="#FFFFFF" corner-roundness="0;0;0;0" buttonSize="25" over-size="11" over-underline="true"></snbuttons></controls></body></config>',
                    externalColor: "Transparent",
                    partnerData: YAHOO.util.Dom.get('gigya_widget-partnerinfo').innerHTML,
                    partnerName: "1401",
                    bulletinChecked: "true"}); }, this, true);

    // when hiding the panel, destroy the gigya widget
    YAHOO.gigya.panel.hideEvent.subscribe(function(){ YAHOO.util.Dom.get('divWildfirePost').innerHTML = ''; }, this, true);

	//add trigger for Show Image on Page
	var showPageImages_triggers = DOM.getElementsByClassName('showPageImages_trigger');
	Event.addListener(showPageImages_triggers, 'click', this.showPageImages ,this);

	//add triggers for Show Images in Post
	var showPostImages_triggers = DOM.getElementsByClassName('showPostImages_trigger');
	Event.addListener(showPostImages_triggers, 'click', this.showPostImages, this);
}

/**
 * Shows/hides a deleted post
 **/
YAHOO.gaia.app.Forum.Detail.prototype.showPost = function(e, scope) {

    // Stop the click action
    Event.stopEvent(e);

    // Get the post to show by looping through all the classes until we find the one that has the ID
    var classes = (this.getAttribute('class')) ? this.getAttribute('class') : this.className;
    if (classes) {
        classes = classes.split(' ');
    }
    else {
        alert("Sorry, we can't show you the deleted post right now. Please contact a developer with the link to this page. 1");
        return;
    }
    for (var i=0; i<classes.length; i++) {
        var tokens = classes[i].split('-');
        if (tokens.length == 3) {
            var id = tokens[2];
            break;
        }
    }

    if (!id) {
        alert("Sorry, we can't show you the deleted post right now. Please contact a developer with the link to this page.");
        return;
    }

    var container = 'post-' + id;
    if (DOM.hasClass(container, 'show')) {
        this.innerHTML = 'Show';
        DOM.removeClass(container, 'show');
    }
    else {
        this.innerHTML = 'Hide';
        DOM.addClass(container, 'show');
    }

}

/*
	Show images that have been hidden in a post
	Laine May 5, 2008
*/
YAHOO.gaia.app.Forum.Detail.prototype.showPostImages = function(e, scope)
{
	//stop the anchor link from clicking through
	Event.stopEvent(e);

	//get post id from the id of the anchor tag
	 var parts = this.id.split('-');
	 var postid = parts[2];

	//get all the image urls in the post
	var post_img_links = DOM.getElementsByClassName('blocked_image_link_'+postid);

	//change all the urls into images
	for(var i=0; i<post_img_links.length; i++)
	{

		//already an image, move on
		if(DOM.getFirstChild(post_img_links[i]).tagName.toLowerCase() =='img') {
			continue;
		}

		//actual url of the image
		var img_url = DOM.getFirstChild(post_img_links[i]).innerHTML;

		//replace url with img tag, this will show the image
		post_img_links[i].innerHTML = '<img src="'+img_url+'">';
	}

	//change the event to be hiding images
	this.innerHTML = 'Hide Blocked Images';
	Event.removeListener(this, 'click', scope.showPostImages);
	Event.addListener(this, 'click', scope.hidePostImages, scope);

}

/*	Show images that have been hidden in a page
	Laine May 5, 2008
*/
YAHOO.gaia.app.Forum.Detail.prototype.showPageImages = function(e, scope)
{
	//stop the anchor link from clicking through
	Event.stopEvent(e);

	//get all the spans that contain the links to blocked images
	var img_links = DOM.getElementsByClassName('blocked_image_link');

	//get the img url
	for(var i=0; i<img_links.length; i++)
	{
		//if it is already an img (via Show Image in Post), skip
		if(DOM.getFirstChild(img_links[i]).tagName.toLowerCase() =='img') {
			continue;
		}

		//actual url of the image
		var img_url = DOM.getFirstChild(img_links[i]).innerHTML;

		//replace url with img tag, this will show the image
		img_links[i].innerHTML = '<img src="'+img_url+'">';
	}

	//change all Show Post Image links to say "Hide Post Images"
	var showPost_triggers = DOM.getElementsByClassName('showPostImages_trigger');
	for(var i=0; i< showPost_triggers.length; i++)
	{
		//skip if it already says "hide"
		if( showPost_triggers[i].innerHTML.toLowerCase().indexOf('hide')!= -1 ) {
			continue;
		}

		showPost_triggers[i].innerHTML = 'Hide Blocked Images';

		//do it here on by one to prevent duplicate listeners
		Event.removeListener(showPost_triggers[i], 'click', scope.showPostImages);
		Event.addListener(showPost_triggers[i], 'click', scope.hidePostImages, scope);

	}

	//change Show Images to Hide Images
	this.innerHTML = 'Hide Blocked Images';
	Event.removeListener(this, 'click', scope.showPageImages);
	Event.addListener(this, 'click', scope.hidePageImages, scope);

}

/*	Hide images that have been shown on a page
*/
YAHOO.gaia.app.Forum.Detail.prototype.hidePageImages = function(e, scope)
{
	//stop the anchor link from clicking through
	Event.stopEvent(e);

	//get all the spans that contain the links to blocked images
	var img_links = DOM.getElementsByClassName('blocked_image_link');

	//get the img url
	for(var i=0; i<img_links.length; i++)
	{
		//not an image, nothing to hide
		if(DOM.getFirstChild(img_links[i]).tagName.toLowerCase() !='img') {
			continue;
		}

		//actual url of the image
		var img_url = DOM.getFirstChild(img_links[i]).src;

		//replace url with img tag, this will show the image
		img_links[i].innerHTML = '<span>' + img_url + '</span>';
	}

	//change all Hide Post Image links to say "Show Post Images"
	var showPost_triggers = DOM.getElementsByClassName('showPostImages_trigger');

	//change text for "hide post images" to "show post images"
	for(var i=0; i< showPost_triggers.length; i++)
	{
		//skip if it already says "Show"
		if( showPost_triggers[i].innerHTML.toLowerCase().indexOf('show')!= -1 ) {
			continue;
		}

		showPost_triggers[i].innerHTML = 'Show Blocked Images';

		//do it here one by one to prevent duplicat listeners
		Event.removeListener(showPost_triggers[i], 'click', scope.hidePostImages);
		Event.addListener(showPost_triggers[i], 'click', scope.showPostImages, scope);
	}

	//change Show Images text to Hide Images text
	this.innerHTML = 'Show Blocked Images';
	Event.removeListener(this, 'click', scope.hidePageImages);
	Event.addListener(this, 'click', scope.showPageImages, scope);
}

/*	Hide images that have been shown on a post
*/
YAHOO.gaia.app.Forum.Detail.prototype.hidePostImages = function(e, scope)
{
	//stop the anchor link from clicking through
	Event.stopEvent(e);

	//get post id from the id of the anchor tag
	 var parts = this.id.split('-');
	 var postid = parts[2];

	//get all the image urls in the post
	var post_img_links = DOM.getElementsByClassName('blocked_image_link_'+postid);

	for(var i=0; i<post_img_links.length; i++)
	{
		//not an image, skip
		if(DOM.getFirstChild(post_img_links[i]).tagName.toLowerCase() !='img') {
			continue;
		}

		//actual url of the image
		var img_url = DOM.getFirstChild(post_img_links[i]).src;

		//replace img tag with anchor tag
		post_img_links[i].innerHTML = '<span>' + img_url + '</span>';
	}


	//chnage it back to "show post images"
	this.innerHTML = 'Show Blocked Images';
	Event.removeListener(this, 'click', scope.hidePostImages);
	Event.addListener(this, 'click', scope.showPostImages, scope);
}

/**
 * Toggles the display of the Gigya Widget
 **/
YAHOO.gaia.app.Forum.Detail.prototype.toggleGigyaWidget = function() {
    if ( ! YAHOO.gigya.panel.cfg.getProperty("visible") ) {
        YAHOO.gigya.panel.show();
    }
    else {
        YAHOO.gigya.panel.hide();
    }
    return false;
}

YAHOO.gaia.app.Forum.Detail.prototype.toggleQuickReply = function(e) {
  Event.preventDefault(e);

  if (!qr.initted) {
    Event.addListener('qr_close', 'click', YAHOO.gaia.app.Forum.Detail.prototype.toggleQuickReply, this);
    Event.addListener('qr_submit', 'click', YAHOO.gaia.app.Forum.Detail.prototype.submitReply, this);

    var url = this.toString();
    qr.nonce_url = url.replace('compose/entry/', 'compose/quickreply/');
    qr.post_url = url.replace('compose/entry/', 'compose/ajaxentry/');

    YAHOO.gaia.app.Forum.Detail.prototype.getNonceCaptcha();
  }

  if (qr.open) {
    // hide it
    DOM.setStyle('qr_container', 'display', 'none');

    qr.open = false;
  } else {
    var target = Event.getTarget(e);
    qr.target = target;

    YAHOO.gaia.app.Forum.Detail.prototype.setQRPosition();

    DOM.get('qr_text').focus();
    DOM.get('qr_text').value = '';

    qr.open = true;
  }
}

YAHOO.gaia.app.Forum.Detail.prototype.submitReply = function(e) {
  Event.preventDefault(e);

  var reply = DOM.get('qr_text').value;
  var captcha_vals = '';

  if ( (qr.nonce != null) && reply.length) {
    if (qr.show_captcha) {
      captcha_vals = '&recaptcha_response_field=' + escape(DOM.get('captcha_response').value) + '&recaptcha_challenge_field=' + escape(qr.captcha.challenge);
    }

    if (qr.posting) {
      return;
    }

    /* prevent multiple submit clicks */
    qr.posting = true;

    YAHOO.util.Connect.asyncRequest('POST', qr.post_url,
      {
        success: function(o) {
          var json = YAHOO.lang.JSON.parse(o.responseText);
          if (json.status) {
            /* omniture logging */
            s.pageName = qr.pageName;
            s.t();

            DOM.setStyle('qr_error', 'display', 'none');
            window.location = json.url;
          } else {
            DOM.setStyle('qr_error', 'display', 'block');
            DOM.get('qr_error').innerHTML = json.message;
            qr.nonce = json.nonce;

            qr.posting = false;
          }
        },
        failure: function() { qr.posting = false; },
        scope: this
      },
      'nonce=' + qr.nonce + '&message=' + escape(reply) + '&action_submit=submit' + captcha_vals
    );
  }
}

YAHOO.gaia.app.Forum.Detail.prototype.setQRPosition = function() {
  var target = qr.target;
  var panel = DOM.get('qr_container');

  //show it
  DOM.setStyle(panel, 'display', 'block');

  var pos = DOM.getRegion(target);

  DOM.setX(panel, pos.left - 67);

  if (pos.top <= 201) {
    DOM.setY(panel, pos.top + 21);
  } else {
    if (qr.show_captcha == false) {
      DOM.setY(panel, pos.top - 210);
    } else {
      DOM.setY(panel, pos.top - 359);
    }
  }
}

YAHOO.gaia.app.Forum.Detail.prototype.getNonceCaptcha = function(e) {
    if (e != undefined) {
      Event.preventDefault(e);
    }

    YAHOO.util.Connect.asyncRequest('GET', qr.nonce_url, {
        success: function(o) {
          var json = YAHOO.lang.JSON.parse(o.responseText);
          if (json.nonce != undefined) {
            qr.nonce = json.nonce;
            qr.pageName = json.pageName;

            if (json.show_captcha) {
              if (qr.initted == false) {
                Event.addListener('qr_new_captcha', 'click', YAHOO.gaia.app.Forum.Detail.prototype.getNonceCaptcha, this);
              }

              qr.show_captcha = json.show_captcha;
              qr.captcha.challenge = json.captcha_challenge;
              qr.captcha.url = json.captcha_img;

              DOM.setStyle('qr_captcha', 'display', 'block');
              DOM.get('captcha_image').src = qr.captcha.url;

              DOM.get('captcha_response').value = '';

              YAHOO.gaia.app.Forum.Detail.prototype.setQRPosition();
            }

            qr.initted = true;
          }
        },
        failure: function() {},
        scope: this
    });
}


YAHOO.util.Event.onDOMReady(function() { new YAHOO.gaia.app.Forum.Detail(); });
