/* Setup namespaces */
if (typeof(BCNTRY) == 'undefined') {BCNTRY = {};}
if (typeof(BCNTRY.swatches) == 'undefined') {BCNTRY.swatches = {};}
if (typeof(BCNTRY.pdp) == 'undefined') {BCNTRY.pdp = {};}
if (typeof(BCNTRY.cpi) == 'undefined') {BCNTRY.cpi = {};}
if (typeof(BCNTRY.review) == 'undefined') {BCNTRY.review = {};}

var _parse_query_params = function(p) {
    var params = [];
    for (var i in p) {
        params.push( i + "=" + encodeURIComponent(p[i]));
    }
    return params.join("&");
};

var connection = false;
function asyncRequest(url, callback, args) { 
    // Only allow one connection at a time
    if (connection) { return; }
    connection = true; 

    yd.addClass(document.body, 'yui-busy');

    yc.asyncRequest('POST', url, {
        timeout: ajax_timeout,
        success: function(o) {
            var json_data = o.responseText;
            var resultObj = {};
            try {
                resultObj = eval( '(' + json_data + ')' );
                if (resultObj.success && callback) {
                    callback.success(resultObj.attributes);
                }
                else if (callback) {
                    callback.error(resultObj);
                }
            }
            catch(e) {
                if (callback) {
                    callback.failure(o, e);
                }
            }
            yd.removeClass(document.body, 'yui-busy');
            connection = false;
        },
        failure: function(o) {
            if (callback) {
                callback.failure(o);
            }
            yd.removeClass(document.body, 'yui-busy');
            connection = false;
        }
    }, _parse_query_params(args));
}



/* Carousel/Scrollies stuff*/

//Constant for the width of each item in a scrolly
BCNTRY.slider_item_width = 75;

//Constructor for BCNTRY.Slider class
BCNTRY.Slider = function (carousel_id, item_array, carousel_list_id, left_arrow, right_arrow, left_arrow_off, right_arrow_off, image_id_base) {
/*
Class: BCNTRY.Slider
Class for the swatch and detail image slider/reel/carousel/scrolly
Constructor parameters:
	carousel_id: HTML id of the carousel
	item_array: array of PDPImages holding the information for each item
	carousel_list_id: HTML id of the carousel list
	left_arrow, right_arrow, left_arrow_off, right_arrow_off: HTML ids for each arrow
	image_id_base: Prefix of HTML id for the images within the items

*/
   var show_arrows = 1;
   
   // Hardcoded width of the other parts of the scrolly, which aren't in 
   // the carousel.  More stable across browsers than dynamic methods of 
   // calculating the width
   var extra_width = 96 + 45*2 +20;
   
   // Calculate the size of the carousel
   var set_size = function (num_items) {
			 num_items = item_array.length;
			 
			 // To be cross-browser - have to add in a fudge-factor
			 var width = $('content').clientWidth ? $('content').clientWidth : $('content').offsetWidth;
			 var available_width = width - extra_width - 25;
			 
			 //alert ('5width: '+width+ ' available_width: '+available_width+' clientWidth: '+$('content').clientWidth+' offsetWidth '+$('content').offsetWidth+' viewport: '+yd.getViewportWidth());
			 num_items_to_show = Math.round((available_width / BCNTRY.slider_item_width) - 0.5);
			 
			 //alert('content_width: '+width+' av width: '+available_width+' num_items_to_show: '+num_items_to_show);
			 
			 // Show navigation arrows depending on how many items and how many 
			 // are showing
			 if (num_items_to_show >= num_items) {
				 show_arrows = 0;
				 yd.setStyle(left_arrow,'display','none');
				 yd.setStyle(right_arrow,'display','none');
				 yd.setStyle(left_arrow_off,'display','none');
				 yd.setStyle(right_arrow_off,'display','none');
			 }
			 else {
				 show_arrows = 1;
				 yd.setStyle(left_arrow,'display','none');
				 yd.setStyle(right_arrow,'display','block');
				 yd.setStyle(left_arrow_off,'display','block');
				 yd.setStyle(right_arrow_off,'display','none');
			 }
	};
	
	// Load the new items
	var load =  function(carousel, start, last, ia) {
		var items;
		if (typeof(slider) !== 'undefined') {
			items = slider.item_array;
		}
		else {
			items = item_array || ia;
		}
		for(var i=start; i<=last; i++) {
			i = parseInt(i,10);
			//alert('about to addItem: '+i+' of '+start+' to '+last);
			carousel.addItem(i, items[i-1].fmtItem(i-1),items[i-1].item_class);
			BCNTRY.pdp_images.tooltips[image_id_base+(i-1)] = new YAHOO.widget.Tooltip('tooltip_'+image_id_base+'_'+(i-1),
				{ context:image_id_base+"_"+(i-1), text: items[i-1].description});
			//alert('item added: '+i+' of '+start+' to '+last);
		}
	};

	// Handler on loading a carousel
	loadInitialItems = function(type, args) {
		var start = args[0];
		var last = args[1]; 
	
		load(this, start, last);	
	};

	// Handler on exposing new items left or right
	loadNextItems = function(type, args) {	
		var start = args[0];
		var last = args[1]; 
		var alreadyCached = args[2];
	
		if(!alreadyCached) {
			load(this, start, last);
		}
	};
	
	
	// Initialize the size of the carousel
	set_size(item_array.length);
	
	// Data structure of the object
	var slider = {
		item_array: item_array,
		left_arrow: left_arrow,
		right_arrow: right_arrow,
		left_arrow_off: left_arrow_off,
		right_arrow_off: right_arrow_off,
		num_items_to_show: num_items_to_show,
		width: function () { 
			return num_items_to_show * BCNTRY.slider_item_width + extra_width+'px';
		},
		
		carousel: new YAHOO.extension.Carousel(carousel_id, 
		{
			numVisible:		Math.min(item_array.length,num_items_to_show),
			animationSpeed:	0.5,
			scrollInc:		 2,
			navMargin:		 5,
			size:			  item_array.length,
			loadInitHandler:   loadInitialItems,
			loadNextHandler:   loadNextItems,
			loadPrevHandler:   loadNextItems,
			prevButtonStateHandler: function (type,args) {
				if (show_arrows) {//alert('prevhandler: '+args[0]);
					if (!args[0]) {
						clearTimeout(this.prevtimer); 
						yd.setStyle(left_arrow,'display','none');
						yd.setStyle(left_arrow_off,'display','block');
						
					} 
					else {
						yd.setStyle(left_arrow,'display','block');
						yd.setStyle(left_arrow_off,'display','none');
					}
				}
			},
			nextButtonStateHandler: function (type,args) {
				if (show_arrows) {
					if (!args[0]) {
						clearTimeout(this.nexttimer); 
						yd.setStyle(right_arrow,'display','none');
						yd.setStyle(right_arrow_off,'display','block');
					} 
					else {
						yd.setStyle(right_arrow,'display','block');
						yd.setStyle(right_arrow_off,'display','none');
					}
				}
			},
			animationMethod: ''
		}
		), //end carousel
		load_externally: function (first,last) { load(this.carousel,first,last, this.item_array);},
		clickHandler: function (e) { 
			var elTarget = YAHOO.util.Event.getTarget(e);	
			while (elTarget.id != carousel_list_id) { 
				if(elTarget.nodeName.toUpperCase() == "LI") { 
					var index = parseInt(elTarget.id.replace(/.*-item-/,''),10);
					var label = elTarget.id.replace(/_carousel-item.*/,'');
					BCNTRY.pdp_images.set_current(item_array,index-1);
					template_links_tl('tr_template', 'PDP:'+label);
				   break; 
				} else { 
				 elTarget = elTarget.parentNode; 
				} 
			}
			return false;
		},

		//searches the content_id in the carousel and makes it the current one.
		set_current_in_carousel_by_id: function(content_id){
			BCNTRY.pdp_images.set_mode(item_array);
			return BCNTRY.pdp_images.set_current_in_carousel_by_id(content_id);
		},
		
		nexttimer: '',
		prevtimer: '',
		scroll_prev: function () {
			clearTimeout(this.nexttimer);
			clearTimeout(this.prevtimer);
			this.carousel.scrollPrev();
			this.prevtimer = setTimeout(function() {slider.scroll_prev();},this.carousel.animationSpeed+7*1000);
		},
		scroll_next: function () {
			clearTimeout(this.nexttimer);
			clearTimeout(this.prevtimer);
			this.carousel.scrollNext();
			this.nexttimer = setTimeout(function(){slider.scroll_next();},this.carousel.animationSpeed+7*1000);
		},
		resize: function () {
			set_size();
			this.carousel.setProperty('numVisible', Math.min(item_array.length,num_items_to_show));
		},
		range_visible: function (first, last) {
			if (first > last) {
				return false;
			}
			if (first < this.carousel.getProperty('firstVisible')) {
			   return false; 
			}
			if (last > (this.carousel.getProperty('firstVisible') + this.carousel.getProperty('numVisible') - 1)) {
			   return false; 
			}
			return true;
		},
		// Move the carousel so the first-last images are potentially visible
		move_to_view: function (first,last) {
			this.carousel.scrollTo(first);
		}
	};

	// Assign events to buttons
	ye.on(right_arrow, 'mouseover', function () {slider.scroll_next(); template_links_tl('tr_template', 'PDP:' + carousel_id + '_right');});
	ye.on(right_arrow, 'mouseout', function () {clearTimeout(slider.nexttimer);});
	ye.on(left_arrow, 'mouseover', function () {slider.scroll_prev(); template_links_tl('tr_template', 'PDP:' + carousel_id + '_left');});
	ye.on(left_arrow, 'mouseout', function () {clearTimeout(slider.prevtimer);});
	return slider;
};



// Listen to the window resize event and redraw the carousel
ye.addListener(window,"resize", function () {
	if (BCNTRY.swatch) {
		BCNTRY.swatch.resize();
		$('available_colors').style.width = BCNTRY.swatch.width();
		$('cpi_views_empty').style.width = BCNTRY.swatch.width();
	}
	if (BCNTRY.detail_images) {
		BCNTRY.detail_images.resize();
		$('more_views').style.width = BCNTRY.detail_images.width();
	}
	if( BCNTRY.customer_product_images ) {
		BCNTRY.customer_product_images.resize();
		$('cpi_views').style.width = BCNTRY.customer_product_images.width();
	}
});
/*End carousel/ slider stuff*/

function AddSwatchToURL(thislink) {
	var imageCGIName = 'swatch'; //The code on the other end of this URL expects this variable
	var imageSrc = '';

	//Default imagename is 'mainimage'
	imageSrc = $('main_product_image').src;

	//Get just the filename of the image (with no path)
	var filename = imageSrc.substring(imageSrc.lastIndexOf('/') + 1, imageSrc.lastIndexOf('.'));

	//Figure out how to append image swatch based on possible presence of query string
	var tmpURL = thislink;

	if (-1 == tmpURL.indexOf('?')) {
		//No querystring on the URL, so we create our own
		tmpURL = tmpURL + '?';
	} else {
		//Append another name/value pair to existing querystring
		tmpURL = tmpURL + '&';
	}

	tmpURL = tmpURL + imageCGIName + '=' + filename;

	//Send it
	window.location = tmpURL;
	return false;
}

function readReview(reviewID, helpful, sku) {
	$(reviewID).helpful_review.value = (helpful === true);
	var scr = new ScReadReview(reviewID, helpful, sku);
	$(reviewID).submit();
	return true;
}

function checkoptions(form) {
	if(form.mv_sku) {
		if(form.mv_sku.length > 1) {
			if(form.mv_sku.selectedIndex === 0) {
				BCNTRY.pdp.none_selected_popup_show();
				if (typeof(ScVariantPop) !== 'undefined') {
					var scv = new ScVariantPop();
				}
				return false;
			}
		}
	}
	return true;
}

function checkqty(elid) {
	if(isNaN(yd.get(elid).value) || (yd.get(elid).value <= 0)) {
		alert('Please enter a valid number in the quantity field');
		yd.get(elid).value = '1';
		yd.get(elid).focus();
		return false;
	}
	return true;
}

function displayPopup(elmID){
	yd.setStyle(elmID,'display','');
}

function hidePopup(elmID){
	yd.setStyle(elmID,'display','none');
}

/*toos*/
if(!BCNTRY.pdp.notify) BCNTRY.pdp.notify={};
BCNTRY.pdp.notify.ProdEventListener = function(sku) {
  this.sku=sku;
};
BCNTRY.pdp.notify.ProdEventListener.prototype = {
  subscribe:function(opts) {
	if(BCNTRY.pdp.successful_submit) return;
	if(!/onQuantityReceived/.test(opts.event)) throw "Invalid Event!";
	var listener = this;
	var callback = {
	  success:function(res) {
		var obj;
		try {
		  obj = eval('('+res.responseText+')');
		}
		catch(an_error) {
		  opts.onFailure(null,listener);
		}
		if(obj.errors) {
		  opts.onFailure(obj,listener);
		}
		else {
		  opts.onSuccess(obj,listener);
		}
	  }
	};
	yc.asyncRequest('POST',opts.url,callback,'sku='+this.sku+'&event='+opts.event+'&email='+opts.email);
  }
};
BCNTRY.pdp.notify.when_stock_show = function() {yd.setStyle('notify_when_stock','display','block'); };
BCNTRY.pdp.notify.when_stock_hide = function() {yd.setStyle('notify_when_stock','display','none');return false;};
BCNTRY.pdp.notify.errors = {
  INVALID_EMAIL:1<<0,
  INVALID_SKU:1<<1,
  UNKNOWN_ERROR:1<<2
};
BCNTRY.pdp.notify.error_messages = {
  INVALID_EMAIL:'Invalid email address ',
  INVALID_SKU:'Not a valid product ',
  UNKNOWN_ERROR:"Oops, something went wrong. Please try again later."
}
BCNTRY.pdp.notify.validate_toos = function(toos_form) {
  var errors = 0;
  if(!/^[^@]+@[^@]+\.[^@]+$/.test(toos_form.notify_email.value) ) {
	errors |= BCNTRY.pdp.notify.errors.INVALID_EMAIL;
  }
  if(!/[A-Z][A-Z0-9][A-Z][0-9]{4}-/.test(toos_form.toos_sku.value)) {
	errors |= BCNTRY.pdp.notify.errors.INVALID_SKU;
  }
  return errors;
};
BCNTRY.pdp.notify.render_errors = function(errors) {
  var error_well;
  if(!(error_well=$('notify_email_error_well'))) {
	error_well= document.createElement('span');
	error_well.setAttribute('class','error');
	error_well.setAttribute('id','notify_email_error_well');			  
  }
  else {
	//clear out error messages
	error_well.innerHTML='';
  }
  var message='';
  for( i in BCNTRY.pdp.notify.errors ) {
	if( BCNTRY.pdp.notify.errors[i] & errors ) {
	  message += BCNTRY.pdp.notify.error_messages[i];
	}	
  }
  error_well.appendChild(document.createTextNode(message));
  $('notify_email_lbl').appendChild(error_well);

};
BCNTRY.pdp.notify.render_success = function(obj) {
  var inp = $('toos_notify');
  var inp_up = inp.parentNode;
  //this can be changed later
  var sp = document.createElement('span');
  sp.setAttribute('id','toos_success_message');
  sp.textContent='Thanks for signing up!';
  inp_up.removeChild(inp);
  inp_up.appendChild(sp);
  setTimeout(function() {var m=$('toos_success_message');m.parentNode.removeChild(m);},1500);
  BCNTRY.pdp.successful_submit=true;
};
BCNTRY.pdp.notify.when_stock_submit = function() {
	if(BCNTRY.pdp.notify.submitting) return false;
	//grab a reference to the sku being submitted
	var toos_form = $('notify_options');
	var errors = BCNTRY.pdp.notify.validate_toos(toos_form);
	if(errors) {
		BCNTRY.pdp.notify.render_errors(errors);
		return false;
	}
	//now that we know the data is valid (on the client site) submit
	//to web service
	BCNTRY.pdp.notify.submitting=true;
	var sku = toos_form.toos_sku.value;

	var listener = new BCNTRY.pdp.notify.ProdEventListener(sku);
  listener.subscribe(
	{
	  url:toos_form.getAttribute('action'),
	  event:'onQuantityReceived',
	  email:toos_form.notify_email.value,
	  onSuccess:function(obj,instance) {
		//track omniture values
		try {
		  template_links_tl('tr_template', 'Notify Me:'+s_sc.pageName);
		}
		catch(err) {
		  //omniture errors shouldn't be visible to the user.
		}
		BCNTRY.pdp.notify.submitting=false;
		BCNTRY.pdp.notify.when_stock_hide();
		BCNTRY.pdp.notify.render_success(obj);
	  },
	  onFailure:function(obj) {
		BCNTRY.pdp.notify.submitting=false;
		if(obj && obj.errors) {		  
		  BCNTRY.pdp.notify.render_errors(obj.errors);
		}
	  }
	}
  );
	return false;
};

BCNTRY.pdp.none_selected_popup = new YAHOO.widget.Panel("none_selected_popup",
{
	close:true,
	visible:false,
	draggable:true,
	modal:true,
	zIndex:500,
	fixedcenter:true
});

BCNTRY.pdp.updateSubmitPanel = function (variant_id) {
	var variant = $(variant_id);
    // FANSTR:QKS5066-FANSTR-S69M:0
	BCNTRY.pdp_images.set_from_dropdown(variant.id);
	variant.selected = true;
	BCNTRY.pdp.none_selected_popup_hide();
	var form = document.flypage;
	form.submit();
};

BCNTRY.pdp.none_selected_popup_hide = function () {
   $('none_selected_popup').style.display = 'none';
   $('select_size').style.visibility = 'visible';
   BCNTRY.pdp.none_selected_popup.hide();
};

BCNTRY.pdp.none_selected_popup_show = function () {
   $('none_selected_popup').style.display = 'block';
   // hide the dropdown bar
   $('select_size').style.visibility = 'hidden';
   BCNTRY.pdp.none_selected_popup.show();
   var none_selected_popup_mask = $('none_selected_popup_mask');
   if (none_selected_popup_mask !== null) {
	   none_selected_popup_mask.onclick = BCNTRY.pdp.none_selected_popup_hide;
	   if (none_selected_popup_mask.style.zIndex >= 500) {
		   none_selected_popup_mask.style.zIndex = 499;
	   }
   }
};

// Main image navigation
BCNTRY.PDPImage = function (img_src, description, main_image_url, large_image_url, 
                                                       sku_part, is_overview, fmtItem, item_class, content_type, 
                                                       profile_url, display_name, helpful_html, id, helpful_count, unhelpful_count ) {
	/* 
	Class: BCNTRY.PDPImage
	Container to hold individual item information for images
	Constructor parameters:
		img_src: URL for the thumbnail image
		description: description of the image
		main_image_url: URL for the main image
		large_image_url: URL for the large image
		sku_part: Associated SKU part for the image
		is_overview: True if an overview detail image
		fmtItem: Function to provide the HTML for the item in the scrolly
		item_class: Class to be added to the <li> for the item in the scrolly
		*/
		description = description.split("&#39;").join("\'");//recode the apostrophe
	return {
		image_src:  img_src,
		description: description,
		main_image_url: main_image_url,
		large_image_url: large_image_url,
		sku_part: sku_part || null,
		is_overview: is_overview,
		fmtItem: fmtItem,
	    item_class: item_class,
        profile_url: profile_url || null,
        content_type: content_type || null,
        display_name: display_name || null,
        helpful_html: helpful_html || null,
        id: id || null,
        helpful_count: helpful_count || null,
        unhelpful_count: unhelpful_count || null
    };
};


BCNTRY.PDPImages = function () {
	/*
	Class: BCNTRY.PDPImages
	Holder for the main navigation of swatch and detail images
	*/
	
	// Helper function to say whether the item does not have associated images
	var is_missing = function (url) {
		if (!url || url == '/images/0' || url == '/images/null') {
			return true;
		}
		if (url.match('missing_image')) {
			return true;
		}
		return false;
	};

	// Object data structure
	var instance = {
		// HTML ID's for the navigation arrows
		left_on: 'prev_main_image_link',
		left_off: 'image_nav_left_off',
		right_on: 'next_main_image_link',
		right_off: 'image_nav_right_off',
		
		// Holder of image information for the two collections that control the main image
		swatches:   [],
		detail_images: [],
		
		// Get the swatch's description given a sku part
		get_swatch_description: function (sku_part) {
			for (var swatch_index in this.swatches) {
				if (this.swatches[swatch_index].sku_part === sku_part) {
					return this.swatches[swatch_index].description;
				}
			}
			return '';
		},

		// Holder for all the tooltips (not used, but needed)
		tooltips: [],
		// The mode is the collection that is currently controlling the main image
		mode:   function () {return this.swatches;},
		// Returns true if there is only one image in the collection
		only_one: function () {
			if (this.mode().length == 1) {
			   return true;
			}
			else {
				var num_with_images = 0;
				for (var i in this.mode()) {
					if (!is_missing(this.mode()[i].main_image_url)) {
						num_with_images++;
					}
				}
				return num_with_images == 1;
			}
		},
		// Show or hide the controls depending on how far through the list we are
		show_hide_controls: function () {
			if (!this.only_one()) {
				
				if (this.first()) {
					yd.setStyle(this.left_on,'display','none');
					yd.setStyle(this.left_off,'display','block');
				}
				else {
					yd.setStyle(this.left_on,'display','block');
					yd.setStyle(this.left_off,'display','none');
				}
				
				if (this.last() ) {
					yd.setStyle(this.right_on,'display','none');
					yd.setStyle(this.right_off,'display','block');
				}
				else {
					yd.setStyle(this.right_on,'display','block');
					yd.setStyle(this.right_off,'display','none');
				}
			}
			else {
				yd.setStyle(this.left_on,'display','none');
				yd.setStyle(this.left_off,'display','none');
				yd.setStyle(this.right_on,'display','none');
				yd.setStyle(this.right_off,'display','none');
			}
		},
		// Highlight the detail images associated with a swatch
		highlight_di: function () {
			
			// Highlighting has been turned off
			return;
		},
		// Sets the collection that is current in the main image
		set_mode: function (new_mode) { 
			this.mode = function () { return new_mode; };
		},
		// The index of the current main image
		current:	0,
        // amount of removed cpis
        removed_items:  0,
        //currently diaplyed items
        displayed_items: function () {
            return this.mode().length - this.removed_items;
        },

		// Returns true if the current image is the first (discounting missing images)
		first: function () {
			if ( this.current === 0) {
				return true;
			}
			else {
				var i = this.current - 1;
				while (is_missing(this.mode()[i].main_image_url)) {
					if (i === 0) {
						return true;	
					}
					i --;
				}
				return false;
			}
		},
	   // Returns true if the current image is the last (discounting missing images)
		last: function () {
			if ( this.current == this.mode().length -1 ) {
				return true;
			}
			else {
				var i = this.current + 1;
				while (is_missing(this.mode()[i].main_image_url)) {
					if (i === this.mode().length-1) {
						return true;
					}
					i++;
				}
				return false;
			}
		},

		//searches the content_id in the carousel and makes it the current one.
		set_current_in_carousel_by_id: function(content_id){
			var content_position = -1;
			var total = this.mode().length;
			//var found = false;
			for( var i=0; i< total; i++ ){
				if(this.mode()[i].id == content_id)
					content_position = i;
			}
			if(content_position == -1)
				return false;
			//look at the displayed items list.
		    total = $('cpi_carousel_list').childNodes.length;
			for(var i = 0; i < total; i++){
				if( $('cpi_carousel_list').childNodes[i].nodeName.toUpperCase() == "LI") {
					var current_img_id = $('cpi_carousel_list').childNodes[i].childNodes[0].name; //get the content id, stored in the img element.
					if(current_img_id == content_id){
						this.current = content_position;
						return true;
					}
				}
			}
			return false;
		},

		set_to_current: function () {
			//get the flagging container if present
			var flag_container = BCNTRY.wall.PDP._getChildElement( $('product_image'), "qanda_dialog" );
			//show the phto description box only for valid contents(reviews, cpi, q & a)
			if( this.mode()[this.current].content_type != null ){
				//set the box data
				var content_type = this.mode()[this.current].content_type;
				$('content_display_profile_link').href = this.mode()[this.current].profile_url;
				$('cpi_display_name').innerHTML = this.mode()[this.current].display_name;
				$('cpi_display_helpful_count').innerHTML = this.mode()[this.current].helpful_count;
				$('cpi_display_unhelpful_count').innerHTML = this.mode()[this.current].unhelpful_count;
				$('content_id').value = this.mode()[this.current].id;
				$('content_type').value = this.mode()[this.current].content_type;
				//set the content id on the helfulness form
				var cpi_form = BCNTRY.wall.PDP._getParentElement( $('content_display_profile_link'), "helpfulness_form" );
				cpi_form.content_id.value = this.mode()[this.current].id;
				//if present set the flagging form cpi info
				if( flag_container != null ){
					var flag_container_div = BCNTRY.wall.PDP._getChildElement( flag_container, "flag_container" );
					var flag_form = BCNTRY.wall.PDP._getChildElement( flag_container_div, "flag_as_offensive" );
					if( content_type == 'cpi')
						flag_form.cpi_id.value = this.mode()[this.current].id;
					else if ( content_type == 'review')
						flag_form.review_id.value = this.mode()[this.current].id;
					else if (content_type == 'question') 
						flag_form.question_id.value = this.mode()[this.current].id;
					else if (content_type == 'answer')
						flag_form.answer_id.value = this.mode()[this.current].id;
				}
				//show the correct flag link
				//yd.removeClass('flag_' + $('content_type').value + '_content', 'hidden_content');
				//show the box
				yd.removeClass('cpi_caption', 'hidden_content');			
			}
			else{
				//hide cpi information box
				yd.addClass('cpi_caption', 'hidden_content');
				//remove old flagging form when switching to another type of images
				if( flag_container != null ){
					//old flag form present, hide it
					yd.addClass( flag_container, 'hidden_content');
				}
			}
			$('main_image_description').innerHTML = this.mode()[this.current].description;
			$('main_product_image').src = this.mode()[this.current].main_image_url;
			$('main_product_image_link').href = this.mode()[this.current].large_image_url;
	   	},
		load_large_image: function () {
			
			if( this.mode()[this.current].content_type == 'cpi' ){
				$('large_product_image').src = BCNTRY.cpi.loading_image_url();
			}
            if (!is_missing(this.mode()[this.current].large_image_url)) {
				// Only reload the image if it isn't the same one
				if (!$('large_product_image').src.match(this.mode()[this.current].large_image_url)) {
					$('large_product_image').src = this.mode()[this.current].large_image_url;
				}
			}
			else {
				$('large_product_image').src = $('large_image_url').value;
			}
		},
		next:   function () {
			if (this.current < this.mode().length - 1) {
				this.current += 1;
				this.set_to_current();
				this.show_hide_controls();
				this.highlight_di();
			}
		},
		previous:   function () {
			if (this.current > 0) {
				this.current -= 1;
				this.set_to_current();
				this.show_hide_controls();
				this.highlight_di();
			}
		},
		set_from_dropdown:  function (id) {
			 var data = id.split(":");
			 this.set_current(this.swatches,parseInt(data[2],10));
		},
		set_current:	function (mode, index) {
			this.set_mode(mode);
		
			if ((index >= 0 && index < mode.length) && (!is_missing(this.mode()[index].image_src))) {
				this.current = index;
				this.set_to_current();
				this.highlight_di();
 
				this.show_hide_controls();
			}
		}
	};

	return instance;  
};



try {
	BCNTRY.pdp_images = new BCNTRY.PDPImages();

	// The objects need dynamic information, so calling functions that exist on the
	// dynamically generated page
	if (typeof(add_swatches) !== 'undefined') {
		add_swatches();
	}
	if (typeof(add_di) !== 'undefined') {
		add_di();
	}
	if( typeof(add_cpi) !== 'undefined') {
		add_cpi();
	}

	BCNTRY.pdp_images.set_mode(BCNTRY.pdp_images.swatches);
	BCNTRY.pdp_images.show_hide_controls();

	//BCNTRY.pdp_images.add_tooltips(BCNTRY.pdp_images.swatches, 'swatch_image');
	//BCNTRY.pdp_images.add_tooltips(BCNTRY.pdp_images.detail_images, 'detail_image',true);
	/*Tabs*/
} catch(e) { }

BCNTRY.pdp.tab = function (tab_id, content_id, code_to_execute) {
	/*
	Class: BCNTRY.pdp.tab
	An object for a wall tab
	Constructor parameters:
		tab_id:  HTML ID of the tab
		content_id: HTML ID of the content within the tab
		code_to_execute: Function to call when the tab is clicked
	*/
	var members = {
		tab_id: tab_id,
		content_id: content_id,
		execute: code_to_execute || function () {},
		fresh: 0
	};
	return members;
};

BCNTRY.pdp.getLimit = function ( tab ) {
	try{ 
		return parseInt( document.getElementById( tab + "_limit_holder").value );
	} catch( e ){}
	return 'all';
};

BCNTRY.pdp.getTypeCount = function( type_holder ){
	//get the count of the contributions type	
	var type_count = 0;
	try{	
		type_count = parseInt( document.getElementById( type_holder ).value );
	}catch( e ){}
	return type_count;
};

BCNTRY.pdp.hideExtraContribs = function( list, limit, type ){
	if( list.childNodes && list.childNodes.length > limit ) {
		var counter = 0;
		var startHiding = false;
		//make sure to show only the specified limit of contributions
		for( var i = 0; i < list.childNodes.length; i++ ){
			if( startHiding ){
				try{
					//lets hide the extra contents
					if( list.childNodes[ i ].id ){
						//make sure is a content of the specified type, that IS NOT a solicit and that IS NOT a just posted item
						if( list.childNodes[ i ].id.indexOf( type ) != -1 && 
								list.childNodes[ i ].id.indexOf('solicit') == -1 && 
									list.childNodes[ i ].id.indexOf('just_posted') == -1 ){

							// Hide the contents but not the solicits or the write new content
							list.childNodes[ i ].style.display = 'none';
						}
					}
				} catch (e){
					//using a TRY-CATCH to hide elements, IE does not support DOM so we cant use instanceof HTMLDivElement
				}
				continue;
			}
			//count displayed items
			if( list.childNodes[ i ].id ) {
				counter = list.childNodes[ i ].id.indexOf( type + '_' ) >= 0 && list.childNodes[ i ].style.display != 'none' ? counter + 1 : counter;
			}
			//if counter equals the limit, hide the rest of elements
			startHiding = counter >= limit;
		}
	}
};

BCNTRY.pdp.manageContribs = function( listId, type, type_holder ){
	//get the contributions list and the defined limit of contributions
	var list = document.getElementById( listId );
	var limit = BCNTRY.pdp.getLimit( type );
	if( limit && limit != 'all' ) {
		//if a limit has been defined
		if( type == 'all' ){
			//if the Show All tab, process all contributions types
			//hide extra contributions
			BCNTRY.wall.PDP.filterContributions( listId, limit );
			//see if we need to show the More Link
			document.getElementById( 'view_all' ).style.display = list.childNodes && list.childNodes.length > limit ? "block" : "none";
		}
		else {
			//see if we need to show the link for the specified contribution type
			var showMoreLink = BCNTRY.pdp.getTypeCount( type_holder ) > limit;
			document.getElementById( 'view_all' ).style.display = showMoreLink ? "block" : "none" ;
			if( showMoreLink ){
				//hide the extra contributions
				BCNTRY.pdp.hideExtraContribs( list, limit, type );
			}
		}
	}
	else{
		//hide the link
		document.getElementById( 'view_all' ).style.display = 'none';
	}
	//set the current tab
	document.getElementById('current_tab').value = type;	
};

BCNTRY.pdp.tabs = {
	// Each tab works by turning on/off elements of certain HTML classes
	show_all_tab: new BCNTRY.pdp.tab('show_all_tab','show_all_content', function () {
		yd.getElementsByClassName('all_heading','div','wall_posts',function (el) {yd.setStyle(el,'display','block');});
		yd.getElementsByClassName('QandA','div','wall_posts',function (el) {yd.setStyle(el,'display','block');});
		yd.getElementsByClassName('QandA_heading','div','wall_posts',function (el) {yd.setStyle(el,'display','none');});
		yd.getElementsByClassName('review','div','wall_posts',function (el) {yd.setStyle(el,'display','block');});
		yd.getElementsByClassName('review_heading','div','wall_posts',function (el) {yd.setStyle(el,'display','none');});
		yd.getElementsByClassName('cpi','div','wall_posts',function (el) {yd.setStyle(el,'display','block');});
		yd.getElementsByClassName('cpi_solicit','div','wall_posts',function (el) {yd.setStyle(el,'display','block');});
		yd.getElementsByClassName('question_solicit','div','wall_posts',function (el) {yd.setStyle(el,'display','block');});
		yd.getElementsByClassName('review_solicit','div','wall_posts',function (el) {yd.setStyle(el,'display','block');});
		BCNTRY.pdp.manageContribs( 'wall_posts', 'all', 'all_count_holder' );
		return;
	}),
	reviews_tab: new BCNTRY.pdp.tab('reviews_tab','reviews_content', function () {
		yd.getElementsByClassName('all_heading','div','wall_posts',function (el) {yd.setStyle(el,'display','none');});
		yd.getElementsByClassName('QandA','div','wall_posts',function (el) {yd.setStyle(el,'display','none');});
		yd.getElementsByClassName('QandA_heading','div','wall_posts',function (el) {yd.setStyle(el,'display','none');});
		yd.getElementsByClassName('review','div','wall_posts',function (el) {yd.setStyle(el,'display','block');});
		yd.getElementsByClassName('review_heading','div','wall_posts',function (el) {yd.setStyle(el,'display','block');});
		yd.getElementsByClassName('cpi','div','wall_posts',function (el) {yd.setStyle(el,'display','none');});
		yd.getElementsByClassName('cpi_solicit','div','wall_posts',function (el) {yd.setStyle(el,'display','none');});
		yd.getElementsByClassName('question_solicit','div','wall_posts',function (el) {yd.setStyle(el,'display','none');});
		yd.getElementsByClassName('review_solicit','div','wall_posts',function (el) {yd.setStyle(el,'display','block');});
		BCNTRY.pdp.manageContribs( 'wall_posts', 'review', 'review_count_holder' );
		return;
	}),
	qanda_tab: new BCNTRY.pdp.tab('qanda_tab','qanda_content',function () {
		yd.getElementsByClassName('all_heading','div','wall_posts',function (el) {yd.setStyle(el,'display','none');});
		yd.getElementsByClassName('QandA','div','wall_posts',function (el) {yd.setStyle(el,'display','block');});
		yd.getElementsByClassName('QandA_heading','div','wall_posts',function (el) {yd.setStyle(el,'display','block');});
		yd.getElementsByClassName('review','div','wall_posts',function (el) {yd.setStyle(el,'display','none');});
		yd.getElementsByClassName('review_heading','div','wall_posts',function (el) {yd.setStyle(el,'display','none');});
		yd.getElementsByClassName('cpi','div','wall_posts',function (el) {yd.setStyle(el,'display','none');});
		yd.getElementsByClassName('cpi_solicit','div','wall_posts',function (el) {yd.setStyle(el,'display','none');});
		yd.getElementsByClassName('question_solicit','div','wall_posts',function (el) {yd.setStyle(el,'display','block');});
		yd.getElementsByClassName('review_solicit','div','wall_posts',function (el) {yd.setStyle(el,'display','none');});
		BCNTRY.pdp.manageContribs( 'wall_posts', 'question', 'question_count_holder' );
		return;
	}),
	cpi_tab: new BCNTRY.pdp.tab('cpi_tab','cpi_content',function () {
		yd.getElementsByClassName('all_heading','div','wall_posts',function (el) {yd.setStyle(el,'display','none');});
		yd.getElementsByClassName('QandA','div','wall_posts',function (el) {yd.setStyle(el,'display','none');});
		yd.getElementsByClassName('QandA_heading','div','wall_posts',function (el) {yd.setStyle(el,'display','none');});
		yd.getElementsByClassName('review','div','wall_posts',function (el) {yd.setStyle(el,'display','none');});
		yd.getElementsByClassName('review_heading','div','wall_posts',function (el) {yd.setStyle(el,'display','none');});
		yd.getElementsByClassName('cpi','div','wall_posts',function (el) {yd.setStyle(el,'display','block');});
		yd.getElementsByClassName('cpi_solicit','div','wall_posts',function (el) {yd.setStyle(el,'display','block');});
		yd.getElementsByClassName('question_solicit','div','wall_posts',function (el) {yd.setStyle(el,'display','none');});
		yd.getElementsByClassName('review_solicit','div','wall_posts',function (el) {yd.setStyle(el,'display','none');});
		BCNTRY.pdp.manageContribs( 'wall_posts', 'cpi', 'cpi_count_holder' );
		return;
	})
};



// Function to be called to switch between tabs (should be in class)
BCNTRY.pdp.switchTab = function (activetab) {
	for (var tab_id in BCNTRY.pdp.tabs) {
		if (BCNTRY.pdp.tabs.hasOwnProperty(tab_id)) {
			$(tab_id).className = 'hidden_tab';
		}
	}
	$(activetab).className = 'active_tab';
	if (typeof(BCNTRY.pdp.tabs[activetab].execute)) {
		BCNTRY.pdp.tabs[activetab].execute();
	}
	yd.setStyle(BCNTRY.pdp.tabs[activetab].content_id,'display','block');
	return;
};
/* End tabs */

/* Start mini profile */
(function(){

	var dialogs = {};
	var ids = 0;

	function createHTML(id, content) {
		var t = document.createElement('div');
		t.id = id;
		yd.addClass(t, 'none');
		yd.addClass(t, 'mini_profile');
		t.innerHTML = '<div class="hd"></div><div class="bd">'+content+'</div><div class="mini_profile_bottom"></div>';
		yd.insertBefore(t, 'wall_posts');
	}

	function coordsInRegion(mouse_coords, region) {
		return (mouse_coords[1] > region.top
			&& mouse_coords[0] > region.left
			&& mouse_coords[1] < region.bottom
			&& mouse_coords[0] < region.right
		);
	}

	function coordsInDialog(mouse_coords, dialog) {
		var region = yd.getRegion(dialog.id);
		var arrow_region = yd.getRegion(dialog.arrow);
		return coordsInRegion(mouse_coords, region) ||
			coordsInRegion(mouse_coords, arrow_region);
	}

	if (typeof(BCNTRY.profile) == 'undefined') { BCNTRY.profile = {}; }
	if (typeof(BCNTRY.profile.widget) == 'undefined') { BCNTRY.profile.widget = {}; }

	BCNTRY.profile.widget.MiniProfile = function(el, args) {
		this.init(el, args);
	}

	var MP = BCNTRY.profile.widget.MiniProfile;

	BCNTRY.profile.widget.MiniProfile._getElFromEvt = function(evt) {
		var el = ye.getTarget(evt);
		if (el.nodeName.toUpperCase() !== 'A') {
			el = el.parentNode;
		}
		return el;
	};

	BCNTRY.profile.widget.MiniProfile.mouseClick = function(evt) {
		var el = MP._getElFromEvt(evt);
		dialogs[el].ignoreError = true;
	};


	BCNTRY.profile.widget.MiniProfile.mouseOver = function(evt) {
		var el = MP._getElFromEvt(evt);
		var username = el.href.match(/profile\/(\d+)/)[1];
		dialogs[el] = dialogs[el] || {};
		var d = dialogs[el];
		d.active = true;

		setTimeout(function() {
			// If they moved their mouse, don't worry about displaying it
			if (!d.active) { return; }

			d.element = el;
			if (!d.dialog) {
				ids++;
				d.id = 'mini_profile_'+ids;

				asyncRequest('/'+BCNTRY.site.catalog+'/profile/'+username+'/mini_profile', {
					success: function(result) {

						try {

						// Profiles without images have a smaller width
						var dialog_width = '443px';
						if (result.image_url) {
							result.image_url = '<img class="user_thumb" src="'+result.image_url+'" />';
						}
						if (result.site_rank.has_tier) {
							result.site_rank.tier_icon_el = '<img src="'+result.site_rank.tier_icon_url+'" alt="'+result.site_rank.tier_text+'" />';
						}
						if (typeof(result.badges) != 'undefined' && result.badges.length > 0) {
							for (var i = 0; i < result.badges.length; i++) {
								result.badges[i].image_html = '<img class="user_badge" src="'+result.badges[i].image_url+'" alt="'+result.badges[i].text+'" />';
							}
						}
						result.passions = result.passions.slice(0,3);
						for(var i=0; i < result.passions.length; i++) {
							result.passions[i] = result.passions[i].name;
						}

						// TODO: Implement this (next iteration?)
						//result.accolades = [{name: 'The North Face - Top Reviewer'},
						//	{name: 'Armani - Top Reviewer'}];
						result.accolades = [];

						// Create/render the dialog
						var content;
						try {
							content = TrimPath.processDOMTemplate('mini_profile_content', result);
						}
						catch(e) {
							content = e.message;
						}
						createHTML(d.id, content);
						yd.removeClass(d.id, 'none');
						d.dialog = new BCNTRY.profile.widget.MiniProfile( d.id, {
							context: [el, 'bl', 'tr'],
							width: dialog_width
						});
						d.dialog.render();
						d.arrow = yd.getElementsByClassName('arrow', 'div', d.id)[0];

						// When they click anywhere in the mini-profile, take them to the profile page
						ye.on(d.id, 'click', function(evt) {
							//omniture tracking
							template_links_tl('tr_template', 'PDP: Profile Link');
							window.location.href = result.profile_url;
						});

						// Hide the dialog when they move the mouse outside of it
						var mouseOutFunc = function(evt) {
							var mouse_coords = ye.getXY(evt);
							if ( !coordsInDialog(mouse_coords, d) ) {
								d.dialog.hide();
							}
						}
						ye.on(d.id, 'mouseout', mouseOutFunc);
						ye.on(d.arrow, 'mouseout', mouseOutFunc);

						// Again, if they moved their mouse, don't worry about displaying it
						if (d.active) {
							d.dialog.show();
						}
						else {
							d.dialog.hide();
						}
						} catch(e) { alert(e.message) }

						track_pdp_mini_proflile_popup();
					},
					failure: function(o) {
						if (!d.ignoreError) {
							alert(o.statusText);
						}
					}
				});
			}
			else {
				d.dialog.cfg.setProperty('context', [el, 'bl', 'tr']);
				d.dialog.show();
			}
		}, 250);
	};

	BCNTRY.profile.widget.MiniProfile.mouseOut = function(evt) {
		var el = MP._getElFromEvt(evt);
		dialogs[el] = dialogs[el] || {};
		var d = dialogs[el];
		d.active = false;

		var mouse_coords = ye.getXY(evt);

		if ( d.dialog && !coordsInDialog(mouse_coords, d) ) {
			d.dialog.hide();
		}
	};

	YAHOO.extend(BCNTRY.profile.widget.MiniProfile, YAHOO.widget.Dialog);

	BCNTRY.cpi._loading_image_url = '';
	BCNTRY.cpi.loading_image_url = function() {
		if (BCNTRY.cpi._loading_image_url === '') {
			BCNTRY.cpi._loading_image_url = $('loading_image_preload').src;
		}
		return BCNTRY.cpi._loading_image_url;
	};
	BCNTRY.cpi.load_large_image = function(el) {
		// This needs to work on either an <a> tag or an outer <span>
		if (el.tagName == 'SPAN') {
			el = el.firstChild;
		}

		var img_url = el.href;
		if (!$('large_product_image').src.match(img_url)) {
			$('large_product_image').alt = '';
			$('large_product_image').src = BCNTRY.cpi.loading_image_url();
			$('large_product_image').src = img_url;
		}
	};

})();

BCNTRY.product_wall_image_zoom = function(node){
    var p = node.parentNode;
    var nodes = yd.getElementsByClassName('cpi_zoom', 'a', p);
    var node = nodes[0];
    return hs.expand(node);
};

// Initialization function to be called when the DOM is ready
ye.onDOMReady(function() {
	if ($('dropdown_gearlists')) {
		BCNTRY.init_dropdown_gearlists();
	}
	//begin pdp notify initialization
		var notify_submit = $('notify_options');
		ye.on(notify_submit,'submit',function(e) {
				ye.preventDefault(e);
				BCNTRY.pdp.notify.when_stock_submit();
		});
	//end pdp notify initialization

	//start track percent page viewed//
	var window_height = yd.getViewportHeight();
	var page_height = yd.getDocumentHeight()
	var min_scroll = yd.getViewportHeight();
	var viewed_percent = 0;
	var viewed_percent_formatted = 1;
	var scrolled_to = 0;

	ye.on(window, 'scroll', function() {
		scrolled_to = YAHOO.util.Dom.getDocumentScrollTop() + window_height;
		if(scrolled_to > min_scroll) {
			min_scroll = scrolled_to;
		}
	});

	ye.on(window, 'unload', function() {
		if(page_height) {
			viewed_percent = min_scroll / page_height;
		}
		viewed_percent = viewed_percent * 100;
		viewed_percent_formatted = Math.ceil(viewed_percent);
		ScTrackPercentPageViewed(viewed_percent_formatted + "%");
	});
	//end track percent page viewed//
	
	// Add listeners for omniture tracking
	if( eval( $('profile_enabled').value ) ) {
		var els = yd.getElementsByClassName('user_profile_link', 'a', 'wall_posts', function(el) {
			ye.on(el, 'click', function(e) { template_links_tl('tr_template', 'PDP: Profile Link') });
		});
	}

	// Add listeners to for the mini profile
	
	if( eval( $('profile_enabled').value ) ) {
		var els = yd.getElementsByClassName('user_profile_link', 'a', 'wall_posts', function(el) {
			ye.on(el, 'mouseover', BCNTRY.profile.widget.MiniProfile.mouseOver, el, true);
			ye.on(el, 'mouseout', BCNTRY.profile.widget.MiniProfile.mouseOut, el, true);
			ye.on(el, 'click', BCNTRY.profile.widget.MiniProfile.mouseClick, el, true);
		});
	}	
	// Create new instances for the swatches, detail images, and cpi
	YAHOO.util.Event.onAvailable('swatch_carousel', function () {
		BCNTRY.swatch = new BCNTRY.Slider('swatch_carousel',BCNTRY.pdp_images.swatches,'swatch_carousel_list','swatch_left','swatch_right','swatch_left_off','swatch_right_off','swatch_image');
		$('available_colors').style.width = BCNTRY.swatch.width();
		$('cpi_views_empty').style.width = BCNTRY.swatch.width();
		YAHOO.util.Event.on("swatch_carousel_list", "click", BCNTRY.swatch.clickHandler); 

	});

	YAHOO.util.Event.onAvailable('di_carousel', function () {
		BCNTRY.detail_images = new BCNTRY.Slider("di_carousel",BCNTRY.pdp_images.detail_images,'di_carousel_list','di_left','di_right','di_left_off','di_right_off','detail_image');
		$('more_views').style.width = BCNTRY.detail_images.width();
		YAHOO.util.Event.on("di_carousel_list", "click", BCNTRY.detail_images.clickHandler); 

	});

	YAHOO.util.Event.onAvailable('cpi_carousel', function () {
		BCNTRY.customer_product_images = new BCNTRY.Slider( "cpi_carousel", BCNTRY.pdp_images.customer_product_images, 
											'cpi_carousel_list', 'cpi_left', 'cpi_right', 'cpi_left_off','cpi_right_off', 'cpi' );
		$('cpi_views').style.width = BCNTRY.customer_product_images.width();
		YAHOO.util.Event.on("cpi_carousel_list", "click", BCNTRY.customer_product_images.clickHandler);
		
	});
	// make sure qty and options are good before submitting pdp to cart
	ye.on('flypage', 'submit', function(e) {
		if(! checkoptions(yd.get('flypage'))) {ye.stopEvent(e);}
		if(! checkqty('mv_order_quantity')) {ye.stopEvent(e);}
		return true;
	});
	//Reading navigation path to see if review_pdp_link was chosen
	var nav_path = _readCookie('nav_path');
	var location = window.location.href;
	if(nav_path.match('R') || location.match('TNF1556') || location.match('TNF2167') || location.match('tnf1556') || location.match('tnf2167')) {
		yd.setStyle('read_all_reviews', 'display', 'none');
	}

	ye.addListener("show_all_tab", "mousedown", function () {BCNTRY.pdp.switchTab('show_all_tab');});
	ye.addListener("reviews_tab", "mousedown", function () {BCNTRY.pdp.switchTab('reviews_tab');});
	ye.addListener("qanda_tab", "mousedown", function () {BCNTRY.pdp.switchTab('qanda_tab');});
	ye.addListener("cpi_tab", "mousedown", function () {BCNTRY.pdp.switchTab('cpi_tab');});
	ye.addListener("see_all_reviews_link", "click", function () {BCNTRY.pdp.switchTab('reviews_tab');});
	ye.addListener("see_all_cpis_link", "click", function () {BCNTRY.pdp.switchTab('cpi_tab');});
	ye.addListener("see_all_q_link", "click", function () {BCNTRY.pdp.switchTab('qanda_tab');});
	
	BCNTRY.pdp.none_selected_popup.render();

    //For large_image_panel
    ye.addListener("enlarge_image_link", "click", function () { 
        hs.expand($('main_product_image_link')); 
        template_links_tl('tr_template', 'PDP:view_large_image_link'); 
        return false 
    });
    ye.addListener("main_product_image_link", "click", function () { 
        //hs.wrapperClassName = 'wide-border';
        hs.expand(this); 
        template_links_tl('tr_template', 'PDP:view_large_image'); 
        return false 
    });

	//make sure if they were on a particular tab that when they reload the page,
	//they stay on that tab.
	if (window.location.href.match('#qanda')) {
		BCNTRY.pdp.switchTab('qanda_tab');
	}
	else if (window.location.href.match('#reviews')) {
		BCNTRY.pdp.switchTab('reviews_tab');
	}
	else if (window.location.href.match('#cpi$')) {
		BCNTRY.pdp.switchTab('cpi_tab');
	}
	else {
		BCNTRY.pdp.switchTab('show_all_tab');
	}

	// add listeners for review solicitation
	YAHOO.util.Event.addListener("review_comments", "focus", function (e) { 
		var el = YAHOO.util.Event.getTarget(e);
		if (el.value == el.form.review_comments_default.value) {
			el.value = '';
		}
		yd.addClass(el.form, 'solicit_expanded');
	});
	YAHOO.util.Event.addListener("review_title", "focus", function (e) { 
		var el = YAHOO.util.Event.getTarget(e);
		if (el.value == "Review Title") {
			el.value = '';
		}
	});
	if($("ratingBar")){
		new BCNTRY.review.controls.rating($('ratingBar'), 'onStar', 'offStar');
	}
}); 

if (typeof(BCNTRY) == 'undefined') { BCNTRY = {}; }
if (typeof(BCNTRY.wall) == 'undefined') { BCNTRY.wall = {}; }
if (typeof(BCNTRY.wall.PDP) == 'undefined') { BCNTRY.wall.PDP = {}; }


(function() {

var
	pdp = BCNTRY.wall.PDP,	// shorthand
	FLAG_ANSWER_ID_PREFIX = 'flag_answer_',
	FLAG_QUESTION_ID_PREFIX = 'flag_question_',
	EDIT_ANSWER_ID_PREFIX = 'answer_edit_',
	EDIT_QUESTION_ID_PREFIX = 'question_edit_',
	EDIT_REVIEW_ID_PREFIX = 'review_edit_',
	FLAG_CPI_ID_PREFIX = 'flag_cpi_',
	FLAG_REVIEW_ID_PREFIX = 'flag_review_',
	FLAG_COMMENT_ID_PREFIX = 'flag_comment_';

BCNTRY.review.validateReviewBeforeSubmitOnClick = function() {
	var review_form = $('submitReviewForm');
	var errors = BCNTRY.review.validate(review_form);
	if(errors) {
	  return false;
	}
	return true;
};

BCNTRY.wall.PDP = {

	messages: {
		cpi: {
			get: {
				ERR_UNKNOWN: 'There was an viewing flagged photo.'
			},
			flag: {
				SUCCESS: 'Good Catch! Thanks for giving everyone the heads up.',
				ERR_UNKNOWN: 'There was an error flagging the photo.',
				ERR_NO_FLAGS: 'Why\'d you flag this?',
				ERR_TOO_MANY: 'You can only flag 2 items without logging in.'
			},
			unflag: {
				SUCCESS: 'Unflagged photo successfully.',
				ERR_UNKNOWN: 'There was an error unflagging the photo.',
				ERR_TOO_MANY: 'You can only unflag 2 items without logging in.'
			},
			delete_cpi: {
				SUCCESS: 'Kapow! Your photo has been deleted.',
				ERR_UNKNOWN: 'There was an error deleting the photo.'
			}
		},
		question: {
			inactivate: {
				SUCCESS: 'Kapow! Your question has been deleted.',
				ERR_UNKNOWN: 'There was an error deleting your question.'
			}
		},
		answer: {
			inactivate: {
				SUCCESS: 'Kapow! Your answer has been deleted.',
				ERR_UNKNOWN: 'There was an error deleting your answer.'
			}
		},
		review: {
			flag: {
			    SUCCESS: 'Good Catch! Thanks for giving everyone the heads up.',
				ERR_UNKNOWN: 'There was an error flagging the review.',
				ERR_NO_FLAGS: 'Why\'d you flag this?',
				ERR_TOO_MANY: 'You can only flag 2 items without logging in.'
			},
			unflag: {
			    SUCCESS: 'Unflagged review successfully.',
			    ERR_UNKNOWN: 'There was an error unflagging the review.',
			    ERR_TOO_MANY: 'You can only unflag 2 items without logging in.'
			},
			inactivate: {
               SUCCESS: 'Kapow! Your review has been deleted.',
               ERR_UNKNOWN: 'There was an error deleting your review.'
            }
		},
		comment: {
			flag: {
			    SUCCESS: 'Good Catch! Thanks for giving everyone the heads up.',
				ERR_UNKNOWN: 'There was an error flagging the comment.',
				ERR_NO_FLAGS: 'Why\'d you flag this?',
				ERR_TOO_MANY: 'You can only flag 2 items without logging in.'
			},
			unflag: {
			    SUCCESS: 'Unflagged comment successfully.',
			    ERR_UNKNOWN: 'There was an error unflagging the comment.',
			    ERR_TOO_MANY: 'You can only unflag 2 items without logging in.'
			}
		}
	},

	//badge hover
	badgeHelpPopup: null,
	badgeHelpIconMouseOver: function(target,description) {
		if ( !this.badgeHelpPopup ) {
			this.badgeHelpPopup = new BCNTRY.community.widget.HelpPopup('badge_help_template');
			this.badgeHelpPopup.render();
		}
		this.badgeHelpPopup.cfg.setProperty('context', [target, 'tl', 'bl']);
		this.badgeHelpPopup.setBody('<p>' + description + '</p>');
		this.badgeHelpPopup.show();
	},
	badgeHelpIconMouseOut: function(evt) {
		 var mouse_coords = ye.getXY(evt);
		 if ( this.badgeHelpPopup && !this._coordsInContainer(mouse_coords, this.badgeHelpPopup) ) {
			this.badgeHelpPopup.hide();
		 }
	},
	_coordsInContainer: function(mouse_coords, container) {
		var region = yd.getRegion(container.id);
		return this._coordsInRegion(mouse_coords, region);
	},

	_coordsInRegion: function(mouse_coords, region) {
		return (mouse_coords[1] >= region.top
			&& mouse_coords[0] >= region.left
			&& mouse_coords[1] <= region.bottom
			&& mouse_coords[0] <= region.right
		);
	 },

	//end badge hover

	add_miniprofile_listeners: function(container) {
		//Make sure the mini profile is enabled
		if( eval( $('profile_enabled').value ) ) {
			yd.getElementsByClassName('user_profile_link', 'a', container, function(el) {
				ye.on(el, 'mouseover', BCNTRY.profile.widget.MiniProfile.mouseOver, el, true);
				ye.on(el, 'mouseout', BCNTRY.profile.widget.MiniProfile.mouseOut, el, true);
			});
		}
	},

	update_content_counter: function ( content_type, content_amount, avg_rank_image ){
		// Get the content counter, the all contents counter and the display element
		var content_counter = document.getElementById( content_type + '_count_holder' );
        var all_counter = document.getElementById( 'all_count_holder' );
        var content_count_display = document.getElementById( content_type + '_count_display' );
        try{
            // Update the content's counter and the all contents counter values
			var numeric_content_counter = parseInt( content_counter.value ) + content_amount;
			var numeric_all_counter = parseInt( all_counter.value ) + content_amount;

            content_counter.value =  numeric_content_counter;
            all_counter.value =  numeric_all_counter;

            // Update the display element
            if( numeric_content_counter == 1 ){
                //first content piece to be uploaded, display the counter display
				yd.removeClass( content_type + '_count', 'hidden_content' );
				
				if( content_type == "review" ) {
					// need to change the reviews text from "Be the first to Testify" to "Testify"
					yd.addClass( 'testify_first_text', 'hidden_content');
					yd.removeClass( 'testify_text', 'hidden_content' );
				}
            }

			if( content_type == "review" ){
				//Update the average item rank image
				document.getElementById( 'review_counter_image' ).innerHTML = "<img src='/images/" + avg_rank_image + "' alt='Average Reviews'/>";			
			} 

			//Update the counter display
			var display_html = content_counter.value;
			display_html += content_type == 'review' ? ' Review' : ( content_type == 'question' ? ' Question' : ' Customer Photo' );
			display_html += numeric_content_counter > 1 ? "s" : "";

			content_count_display.innerHTML = display_html;
       	} catch( e ){
			alert( "Unable to update counters" );
		}
		
	},

	ask_question_onclick: function(form) {
		var q = new BCNTRY.wall.QAndA.Question({
			question_id: form.question_id.value,
			content: form.question_content.value,
			association_type: 'product',
			association: $('association').value
		});

		q.invalidAssociation.subscribe(function(e, msg) {
			q.set_error_message(form, msg);
		});
		q.invalidAssociationType.subscribe(function(e, msg) {
			q.set_error_message(form, msg);
		});
		q.invalidContent.subscribe(function(e, msg) {
			q.set_error_message(form, "We think you forgot something.  Please type your question below.");
		});

		var p = this;

		q.submit({
			success: function(o) {
				var container = p._getParentElement(form, 'QandA');
				q.messaging.question = 'Thanks! We\'re sure others are wondering the same thing.';
				container.innerHTML = q.html();
				p.add_miniprofile_listeners(container);
				
				//Update the question counter by one
				BCNTRY.wall.PDP.update_content_counter( 'question', 1 );

				ScSubmitQandA('Q', 'new');
			},
			failure: function(o, e) {
				if (o.status != -1) {
					// Get the error information
					var json_data = o.responseText;
					var resultObj = {};
					json_data = json_data.replace(/\n/ig,' ');	
					try{
						resultObj = eval( '(' + json_data + ')' );
					}catch(e){
						alert("BCNTRY.wall.PDP: error parsing JSON:\n" + e.message);
					}
					if( resultObj.error_code && resultObj.error_code == 15 && resultObj.newurl ) {
						//User tried to submit a question using the "login form" redirect to the proper page
						window.location.href = resultObj.newurl;
					}
					else {
						var error = 'There was an error submitting the question';
						if (e) {
							error += ":\n" + e.message;
						}
						ajax_error(o, error, 'ask_question_onclick');
					}
				}
			},
			error: function(o) {
				q.set_error_message(form, o.errorMessage);
			}
		});
	},

	upload_photo_submit_onclick: function(form) {
		var ret = true;
	   	if (!(form.title.value.length > 0)) {
			ret = false;
			yd.setStyle('title_error', 'display', 'block');
			yd.setStyle('photo_title_lbl', 'color', 'red');
	   	}
	   	if (!(form.cust_image.value.length > 0)) {
			ret = false;
			yd.setStyle('cust_image_error', 'display', 'block');
			yd.setStyle('cust_image_lbl', 'color', 'red');
	   	}
	   	if (form.description.value.length > 10000) {
			ret = false;
			yd.setStyle('description_error', 'display', 'block');
			yd.setStyle('photo_desc_lbl', 'color', 'red');
	   	}
		return ret;
	},

	edit_question_submit_onclick: function(form) {
		var q = new BCNTRY.wall.QAndA.Question({
			question_id: form.question_id.value,
			content: form.question_content.value,
			association_type: 'product',
			association: $('association').value
		});

		q.invalidAssociation.subscribe(function(e, msg) {
			q.set_error_message(form, msg);
		});
		q.invalidAssociationType.subscribe(function(e, msg) {
			q.set_error_message(form, msg);
		});
		q.invalidContent.subscribe(function() {
			q.set_error_message(form, "We didn't get your edit.  Please enter it");
		});

		var p = this;

		q.submit({
			success: function(o) {
				var container = p._getParentElement(form, 'QandA');
				q.messaging.question = 'Thanks for editing your question, ' + q.obj.user.display_name + '.';
				container.innerHTML = q.html();
				p.add_miniprofile_listeners(container);
				ScSubmitQandA('Q', 'edit');
			},
			failure: function(o, e) {
				if (o.status != -1) { // Ignore aborts
					var error = 'There was an error editing the question';
					if (e) {
						error += ":\n" + e.message;
					}
					ajax_error(o, error, 'ask_question_onclick');
				}
			},
			error: function(o) {
				q.set_error_message(form, o.errorMessage);
			}
		});
	},

	toggle_comments_onclick: function(el, content_type, content_id ) {
		var post_el = this._getParentElement(el, content_type);
		var threaded_comments = 'threaded_comments_' + content_type;
		var els = yd.getElementsByClassName(threaded_comments, 'div', post_el);
		if (els.length < 1) {
			alert('missing comments element');
		}
		comments_el = els[0];

		//Element that indicates if the comments are expanded 
		var comment_new = this._getChildElement(comments_el, 'new_comment');
		if(comment_new){
			//If comments are expanded, then collapse them
			var com = (yd.getElementsByClassName('the_comments', 'div', post_el))[0];
			for(var i = 0; i < com.childNodes.length; i++){
				if(com.childNodes[i].className != null && com.childNodes[i].className == threaded_comments)
					comments_el.innerHTML = ''; 
			}
		}
		else{
			var cc = new BCNTRY.wall.CommentCollection({
				content_type: content_type,
				content_id:   content_id
			});
			var p = this;
			cc.load({
				success: function(o) {
					comments_el.innerHTML = cc.html();
					p.add_miniprofile_listeners(comments_el);
				},
				failure: function() {
					//TODO: prettier error message in the UI, not an alert
					alert('communication problem when loading comments!');
				},
				error: function(r) {
					//TODO: prettier error message in the UI, not an alert
					alert('loading comments failed! ' + r.errorMessage);
				}
			});
		}
	},

	// Makes its way up the element heirarchy until it reaches the 'parent' element
	// of the given classname
	_getParentElement: function(el, classname) {
		while( (el = el.parentNode) ) {
			if (el.className === classname) {
				return el;
			}
		}
	},

	_getChildElement: function(el, classname) {
		return yd.getFirstChildBy( el, function(o) { return (o.className === classname); });
	},

	set_error_message: function(el, message) {
		if (el.className != 'error_message') {
			el = yd.getElementsByClassName('error_message', 'div', el)[0];
		}

		var s = "<p>${message}</p>".process({ message: message});
		el.innerHTML = s;
	},
	
	// Submits an answer once the "save" button is pressed for both edited and adding an answer
	comment_onclick: function(form) {

		var content_el = this._getParentElement(form, form.content_type.value);
        var els = yd.getElementsByClassName('threaded_comments_' + form.content_type.value, 'div',content_el);
		if (els.length < 1) {
        	alert('missing comments element');
		}
        var comments_el = els[0];

		//Element that indicates if the comments are expanded 
		var comment_new = this._getChildElement(comments_el, 'new_comment');
		
		var a = new BCNTRY.wall.Comment({
			content_id: form.content_id.value,
			content_type: form.content_type.value,
			body: form.comment_content.value,
            comment_new : comment_new
		});
		var comment_el = this._getParentElement(form, 'inline_solicitation');
		var summary_el = this._getParentElement(form, 'the_comments');
		summary_el = this._getChildElement(summary_el, 'comment_summary');
		var p = this;
		// Render the rich text editor (if there is one)
		a.submit({
			success: function(o) {
					a.message =  '... Thanks for the comment!';
					if( a.obj.comment.comment_count == 0)
						a.obj.comment.comment_count = parseInt(summary_el.id) + 1; //the comment_count was stored as id attribute

					summary_el.innerHTML = a.html_summary();
					p.add_miniprofile_listeners(summary_el);
					
					// TODO: Track OMNITURE ScSubmitQandA('C', 'new');
					if(comment_new){
						comment_new.innerHTML = a.html_just_posted();
						form.parentNode.innerHTML = '';
						p.add_miniprofile_listeners(comment_new);
					}else{
						comments_el.innerHTML = a.all_comments_html();
                        form.parentNode.innerHTML = '';
                        p.add_miniprofile_listeners(comments_el);
					}
					window.location.href = '#comment_'+ a.obj.comment.id;
			},
			failure: function(o, e) {
				if (o.status != -1) {
					// Get the error information
					var json_data = o.responseText;
					var resultObj = {};
					json_data = json_data.replace(/\n/ig,' ');
					try{
						resultObj = eval( '(' + json_data + ')' );
					}catch(e){
						alert("BCNTRY.wall.PDP: error parsing JSON:\n" + e.message);
					}
					if( resultObj.error_code && resultObj.error_code == 15 && resultObj.newurl ) {
						//User tried to submit an answer  using the "login form" redirect to the proper page
						window.location.href = resultObj.newurl;
					}
					else {
						var error = 'There was an error submitting the comment';
						if (e) {
							error += ":\n" + e.message;
						}
						ajax_error(o, error, 'comment_onclick');
					}
				}
			},
			error: function(o) {
				a.set_error_message(comment_el, o.errorMessage);
			}
		});
	},


	// Submits an answer once the "save" button is pressed for both edited and adding an answer
	answer_question_onclick: function(form) {
		var a = new BCNTRY.wall.QAndA.Answer({
			question_id: form.question_id.value,
			answer_id: form.answer_id.value,
			content: form.answer_content.value,
			association: $('association').value,
			association_type: 'product'
		});
		var qanda_el = this._getParentElement(form, 'QandA');

		a.invalidQuestionID.subscribe(function(e, msg) {
			a.set_error_message(qanda_el, msg);
		});
		a.invalidContent.subscribe(function() {
			a.set_error_message(qanda_el, "Your response wasn't entered.  Please answer below.");
		});

		var p = this;
		// Render the rich text editor (if there is one)
		a.submit({
			success: function(o) {
				if (form.answer_edit) { // Editing an existing question
					a.messaging.answer = 'Thanks for improving this answer, ' + a.obj.answer.user.display_name + '.';
					a.messaging.answer_id = a.obj.answer.answer_id;
					ScSubmitQandA('A', 'edit');
				}
				else {
					a.messaging.answer = a.obj.answer.user.display_name + '... You rule.  Thanks for helping out';
					a.messaging.answer_id = a.obj.answer.answer_id;
					ScSubmitQandA('A', 'new');
				}
				qanda_el.innerHTML = a.html();
				p.add_miniprofile_listeners(qanda_el);
			},
			failure: function(o, e) {
				if (o.status != -1) {
					// Get the error information
					var json_data = o.responseText;
					var resultObj = {};
					json_data = json_data.replace(/\n/ig,' ');
					try{
						resultObj = eval( '(' + json_data + ')' );
					}catch(e){
						alert("BCNTRY.wall.PDP: error parsing JSON:\n" + e.message);
					}
					if( resultObj.error_code && resultObj.error_code == 15 && resultObj.newurl ) {
						//User tried to submit an answer  using the "login form" redirect to the proper page
						window.location.href = resultObj.newurl;
					}
					else {
						var error = 'There was an error submitting the answer';
						if (e) {
							error += ":\n" + e.message;
						}
						ajax_error(o, error, 'answer_question_onclick');
					}
				}
			},
			error: function(o) {
				a.set_error_message(qanda_el, o.errorMessage);
			}
		});
	},

	// Shows the "Edit Answer" dialog
	improve_answer_onclick: function(el, question_id) {
		var ans_el = this._getParentElement(el, 'answer');
		var answer_id = ans_el.id.split('_')[1];
		var body = this._filter_qanda_html($('answer_' + answer_id + '_body').value);
		var img_url = $('answer_' + answer_id + '_img_url').value;

		var t = TrimPath.processDOMTemplate("qanda_new_answer", { 
			question_id: question_id,
			answer_id: answer_id,
			content: body,
			img_el: (img_url.length > 0)
				? '<img class="content_image" src="' + img_url + '" />'
				: undefined
		});

		var id = EDIT_ANSWER_ID_PREFIX + question_id;
		var r_el = $(id);
		if ( !r_el ) {
			this._remove_dialog(ans_el);
			r_el = this._create_dialog(t);
			r_el.id = id;
			ans_el.appendChild(r_el);
		}
	},

	// Shows the "Edit Review" dialog
	edit_review_onclick: function(el, review_id) {
		var rev_el  = this._getParentElement(el, 'review');
		var img_url = $('review_' + review_id + '_img_url').value;
		var args = {
			id: review_id,
			title: $('review_' + review_id + '_title').value,
			rank: $('review_' + review_id + '_rank').value,
			body: $('review_' + review_id + '_body').value,
			img_el: (img_url.length > 0)
				? '<img class="content_image" src="' + img_url + '" />'
				: undefined
		};
		var t = TrimPath.processDOMTemplate('template_edit_review', args);
		var id = EDIT_REVIEW_ID_PREFIX + review_id;
		var dialog = $(id);
		if (!dialog) {
			dialog = this._create_dialog(t);
			dialog.id = id;
			var comments_el = this._getParentElement(el, 'review_item').nextSibling;
			var ratingBarEl = this._getChildElement(yd.getFirstChild(dialog), 'ratingBar');
			new BCNTRY.review.controls.rating(ratingBarEl, 'onStar', 'offStar');
			rev_el.insertBefore( dialog, comments_el);//the edit review dialog appears before the comments area
		}
	},

	// Closes a "dialog" (flagging a question, answer, etc)
	// If a classname is specified, it looks up the dom tree until that class is found
	close_dialog_onclick: function(el) {
		if (el.className !== 'qanda_dialog') {
			el = this._getParentElement(el, "qanda_dialog");
		}
		el.parentNode.removeChild(el);
	},

	filterContributions: function( list_name, fixed_number ){
		var list = document.getElementById( list_name );
		if( list.childNodes && list.childNodes.length > fixed_number ){
			for( var i = fixed_number; i < list.childNodes.length; i++  ){
				//Hide extra content except for solicit items and just posted items
				if( list.childNodes[ i ].id && 
						list.childNodes[ i ].id.indexOf( 'solicit' ) == -1 && 
							list.childNodes[ i ].id.indexOf('just_posted') == -1 ){
					//set display none to the excess of contributions
					list.childNodes[ i ].style.display = 'none';
			   }
			}//end for
		}		
	},

	//method to get all contributions for an specific sku on the PDP
	show_all_contributions: function( sku, tab_holder ) {
		var show_all_contributions_url = "/" + BCNTRY.site.catalog + '/tribe/show_all_contributions';
		var tab = document.getElementById( tab_holder ).value;
		var args = {
			sku: sku,
			tab: tab
		 };
		var p = this;
		var c = {
			success: function(o){
				//load the new content
				document.getElementById('show_all_content').innerHTML = o.contributions;
				//From now on, everytime we come back to this tab show all contributions
				document.getElementById( o.tab + '_limit_holder').value = 'all';
				if( o.logged_user == 1 ) {
					//if the user is loggedin, initialize the reviews elements
					BCNTRY.review.init();
				}
				p.add_miniprofile_listeners($('wall_posts'));
				//execute the filter depending on the selected tab
				if( o.tab == 'all' ){
					BCNTRY.pdp.switchTab('show_all_tab');
				}
				else if( o.tab == 'review' ){
					BCNTRY.pdp.switchTab('reviews_tab');
				}
				else if ( o.tab == 'question' ) {
					BCNTRY.pdp.switchTab('qanda_tab');
				}
				else if ( o.tab == 'cpi' ) {
					BCNTRY.pdp.switchTab('cpi_tab');
				}
			},
			failure: function(o, e) {
				var error = 'There was an error displaying contributions';
				if (e) {
					error += ":\n" + e.message;
				}
				ajax_error(o, error, 'show_all_contributions');
			},
			error: function(o) {
				ajax_error("Error displaying contributions");
			}

		};
		BCNTRY.wall.Post.prototype.asyncRequest( show_all_contributions_url, c, args );
	},



	// Removes a QandA dialog (for whatever reason) by searching the dom tree for
	// an element with a class named 'qanda_dialog', and removing that element if found
	_remove_dialog: function(parent_el) {
		if (!parent_el) { return; }
		var dialog_el = yd.getElementsByClassName('qanda_dialog', 'div', parent_el)[0];
		if (dialog_el) {
			dialog_el.parentNode.removeChild(dialog_el);
		}
	},

	// Creates a dialog filled with the specified html, and returns a DOM element
	_create_dialog: function(html) {
		var el = document.createElement("div");
		el.className = 'qanda_dialog';
		el.innerHTML = html;
		return el;
	},

	// Filters the html that is auto-populated from the page (within the div) to be placed
	// in the textbox 
	_filter_qanda_html: function(html) {
		html = html.replace(/^[\n ]+/, '');
		html = html.replace(/[\n ]+$/, '');
		html = html.replace(/<\/?p>/ig, '');
		html = html.replace(/<br ?\/?>/gi, "\n");
		html = html.replace(/<wbr ?\/?>/gi, '');
		return html;
	},

	// Pops open the "flag_cpi" dialog
    flag_cpi_onclick: function(el, cpi_id, cpi_container, is_from_carousel ) {
        //if the parent is not defined then search for it, otherwise use the parent passed as a parameter
        var cpi_el = cpi_container == undefined ? this._getParentElement(el, 'cpi_item') : cpi_container;
		var t = TrimPath.processDOMTemplate("template_flag_content", {
		    content_type: 'cpi',
            is_from_carousel: false,
            cpi_id: cpi_id,
            content_id: cpi_id,
            is_from_carousel: is_from_carousel
		});
		var id = FLAG_CPI_ID_PREFIX + cpi_id;
		var r_el = $(id);
		if ( !r_el ) {
			r_el = this._create_dialog(t);
			r_el.id = id;
			cpi_el.appendChild(r_el);
		}
		//make sure the form is not hidden
		yd.removeClass( $(id), 'hidden_content' );
	},
	
	// Pops open the "flag_content" dialog
    flag_content_onclick: function(el, content_id, content_type, content_container, is_from_carousel ) {
        //if the parent is not defined then search for it, otherwise use the parent passed as a parameter
        var content_el = content_container == undefined ? this._getParentElement(el, content_type + '_item') : content_container;
		var t = TrimPath.processDOMTemplate("template_flag_content", {
		    content_type: content_type,
            is_from_carousel: false,
            content_id: content_id,
			question_id: 0,
            is_from_carousel: is_from_carousel
		});
		var id;
		if(content_type == 'cpi')
			id = FLAG_CPI_ID_PREFIX + content_id;
		else if (content_type == 'review')
			id = FLAG_REVIEW_ID_PREFIX + content_id;
		else if (content_type == 'question')
			id = FLAG_QUESTION_ID_PREFIX + content_id;
		else if (content_type == 'answer')
			id = FLAG_ANSWER_ID_PREFIX + content_id;
			
		var r_el = $(id);
		if ( !r_el ) {
			r_el = this._create_dialog(t);
			r_el.id = id;
			content_el.appendChild(r_el);
		}
		//make sure the form is not hidden
		yd.removeClass( $(id), 'hidden_content' );
	},

	// Unflags flagged content
	unflag_cpi_onclick: function(el, cpi_id) {
		if (BCNTRY.wall.connection) { return }
		var container = this._getParentElement(el, 'cpi');
		var cpi = new BCNTRY.wall.CPI({ cpi_id: cpi_id });
		var t = this;
		cpi.unflag({
			success: function(a) {
				cpi.obj.message = t.messages.cpi.unflag.SUCCESS;
				container.innerHTML = TrimPath.processDOMTemplate("template_cpi_full", cpi.obj);
			},
			failure: function(o, e) {
				var error = t.messages.cpi.unflag.ERR_UNKNOWN;
				if (e) {
					error += ":\n" + e.message;
				}
				ajax_error(o, error, 'unflag_cpi_onclick');
			},
			error: function(o) {
				var msg = t.messages.cpi.unflag.ERR_UNKNOWN;
				if (o.attributes.failure_type == 'TOO_MANY') {
					msg = t.messages.cpi.unflag.ERR_TOO_MANY;
				}
				t.set_error_message(container, msg);
			}
		});
	},

	inactivate_question_submit_onclick: function(el, question_id) {
		try{
		if (BCNTRY.wall.connection) { return }
		var q = new BCNTRY.wall.QAndA.Question({ question_id: question_id });
		var container = this._getParentElement(el, 'QandA');
		var t = this;
		q.inactivate({
			success: function(a) {
				q.messaging.question  = t.messages.question.inactivate.SUCCESS;
				container.innerHTML = q.html();
				t.add_miniprofile_listeners(container);
			},
			error: function(o) {
				t.set_error_message(container, t.messages.question.inactivate.ERR_UNKNOWN);
			},
			failure: function(o, e) {
				error = '';
				if (e) {
					error += "\n" + e.message;
				}
				ajax_error(o, error, 'inactivate_question_submit_onclick');
			}
		});
		}catch(e){alert(e.message)}
	},
	inactivate_answer_submit_onclick: function(el, question_id, answer_id) {
		try{
		if (BCNTRY.wall.connection) { return }
		var container = this._getParentElement(el, 'answer');
		var a = new BCNTRY.wall.QAndA.Answer({ question_id: question_id, answer_id: answer_id });
		var t = this;
		a.inactivate({
			success: function(o) {
				var container = t._getParentElement(el, 'QandA');
				if (a.answer) {
					a.messaging.answer	= t.messages.answer.inactivate.SUCCESS;
					a.messaging.answer_id = a.obj.answer.answer_id;
				}
				else {
					a.messaging.question = t.messages.answer.inactivate.SUCCESS;
				}
				container.innerHTML = a.html();
			},
			error: function(o) {
				t.set_error_message(container, t.messages.answer.inactivate.ERR_UNKNOWN);
			},
			failure: function(o, e) {
				error = '';
				if (e) { error += "\n" + e.message }
				ajax_error(o, error, 'inactivate_question_submit_onclick');
			}
		});
		}catch(e){alert(e.message)}
	},

   /// Inactivates a review
   inactivate_review_submit_onclick: function(el, review_id) {
       if (BCNTRY.wall.connection) { return }
           var container = this._getParentElement(el, 'review');
       var review = new BCNTRY.wall.Review({ review_id: review_id });
       var t = this;
       review.inactivate({
           success: function(a) {
                   review.obj.message = t.messages.review.inactivate.SUCCESS;
                   container.innerHTML = TrimPath.processDOMTemplate("content_deleted_full", review.obj);
               },
           failure: function(o, e) {
                   var error = t.messages.review.inactivate.ERR_UNKNOWN;
                   if (e) {
                       error += ":\n" + e.message;
                   }
                   ajax_error(o, error, 'inactivate_review_submit_onclick');
               }
       });
   },


	// Inactivates a cpi
	inactivate_cpi_submit_onclick: function(el, cpi_id) {
		if (BCNTRY.wall.connection) { return }
		var container = this._getParentElement(el, 'cpi');
		var cpi = new BCNTRY.wall.CPI({ cpi_id: cpi_id });
		var t = this;
		cpi.inactivate({
			success: function(a) {
				cpi.obj.message = t.messages.cpi.delete_cpi.SUCCESS;
				container.innerHTML = TrimPath.processDOMTemplate("content_deleted_full", cpi.obj);
			},
			failure: function(o, e) {
				var error = t.messages.cpi.delete_cpi.ERR_UNKNOWN;
				if (e) {
					error += "\n" + e.message;
				}
				ajax_error(o, error, 'inactivate_cpi_onclick');
			},
			error: function(o) {
				t.set_error_message(container, t.messages.cpi.delete_cpi.ERR_UNKNOWN);
			}
		});
	},

	//Saves the selected flags for a given cpi from the carousel
	flag_carousel_cpi_submit_onclick: function( flag_form ){
		//allow just one connection at a time
		if (BCNTRY.wall.connection) { return }
		//make the form unique
		flag_form.id = 'flag_form_' + flag_form.cpi_id.value;
		var flag_panel = this._getParentElement(flag_form, 'flag_container');
		//get the flagging data
		var flag_description = flag_form.flag_description.value;
		var cpi_id = flag_form.cpi_id.value;
		var cpi = new BCNTRY.wall.CPI({ cpi_id: cpi_id });
		var t = this;
		//execute flagging
		cpi.flag(flag_description, {
			success: function(a) {
				cpi.obj.message = t.messages.cpi.flag.SUCCESS;
				//Hide the "view image" link
				cpi.obj.display = 'none';
				t.update_carousel_after_flag();
				//old flag form present, remove it
				flag_form.parentNode.removeChild(flag_form);
				//flag_form.innerHTML = TrimPath.processDOMTemplate("template_cpi_full", cpi.obj);
				//set the same flagged content on the wall
				cpi.obj.display = 'flagged';
				$('cpi_' + cpi.cpi_id ).innerHTML = TrimPath.processDOMTemplate("template_cpi_full", cpi.obj);

			},
			failure: function(o, e) {
                var error = t.messages.cpi.flag.ERR_UNKNOWN;
                if (e) {
                    error += ":\n" + e.message;
                }
                ajax_error(o, error, 'flag_carousel_cpi_submit_onclick');
            },
            error: function(o) {
                var msg = t.messages.cpi.flag.ERR_UNKNOWN;
                if (o.attributes.failure_type == 'TOO_MANY') {
                    msg = t.messages.cpi.flag.ERR_TOO_MANY;
                }
                t.set_error_message(flag_panel, msg);
            }

		});
		
	}, 

	// Saves the selected flags for a given cpi
	flag_cpi_submit_onclick: function(flag_form) {
		if (BCNTRY.wall.connection) { return }
		var cpi_id = flag_form.cpi_id.value;
		var flag_description = flag_form.flag_description.value;
		var container = this._getParentElement(flag_form, 'cpi');
		var flag_panel = this._getParentElement(flag_form, 'flag_container');
		var cpi = new BCNTRY.wall.CPI({ cpi_id: cpi_id });
		var t = this;
		cpi.flag(flag_description, {
			success: function(a) {
				cpi.obj.message = t.messages.cpi.flag.SUCCESS;
				container.innerHTML = TrimPath.processDOMTemplate("template_cpi_full", cpi.obj);
				//update carousel
				if(cpi.obj.image_url_small) {
					var current_item_array;
					var current_index = -1;
					if( BCNTRY.pdp_images.mode()  != BCNTRY.pdp_images.customer_product_images ){
						current_item_array = BCNTRY.pdp_images.mode();
						current_index = BCNTRY.pdp_images.current;
					}
					//set the flagged content as current in the carousel, then remove it
					if( BCNTRY.customer_product_images.set_current_in_carousel_by_id( cpi_id ) )
						//remove the content photo from the carousel
						t.update_carousel_after_flag();
					//if the original carousel was other than the gear/content photos, restore it. 
					if(current_index != -1)
						BCNTRY.pdp_images.set_current(current_item_array , current_index);
				}
			},
			failure: function(o, e) {
				var error = t.messages.cpi.flag.ERR_UNKNOWN;
				if (e) {
					error += ":\n" + e.message;
				}
				ajax_error(o, error, 'flag_cpi_submit_onclick');
			},
			error: function(o) {
				var msg = t.messages.cpi.flag.ERR_UNKNOWN;
				if (o.attributes.failure_type == 'TOO_MANY') {
					msg = t.messages.cpi.flag.ERR_TOO_MANY;
				}
				t.set_error_message(flag_panel, msg);
			}
		});
	},

	// Shows flagged content
	flag_cpi_show_onclick: function(el, cpi_id) {
		if (BCNTRY.wall.connection) { return }
		var container = this._getParentElement(el, 'cpi');
		var cpi = new BCNTRY.wall.CPI({ cpi_id: cpi_id });
		var p = this;
		cpi.showFlagged({
			success: function(a) {
				container.innerHTML = cpi.html();
				p.add_miniprofile_listeners(container);
			},
			failure: function(o, e) {
				var error = 'There was an error showing the flagged photo';
				if (e) {
					error += ":\n" + e.message;
				}
				ajax_error(o, error, 'flag_cpi_show_onclick');
			},
			error: function(o) {
				var msg = p.messages.cpi.get.ERR_UNKNOWN;
				p.set_error_message(container, msg);
			}
		});
	},

	//Saves the selected flags for a given answer from the carousel
	flag_carousel_answer_submit_onclick: function( flag_form ){
		//allow just one connection at a time
		if (BCNTRY.wall.connection) { return }
		//make the form unique
		var answer_id = flag_form.answer_id.value;
		flag_form.id = 'flag_form_' + answer_id;

		var flag_panel = this._getParentElement(flag_form, 'flag_container');
		//get the question_id for this answer
		var ans_el = $('answer_' + answer_id ).parentNode;
		var question_id = ans_el.id.split('_')[1];

		//get the flagging data
		var flag_description = flag_form.flag_description.value;
		var a = new BCNTRY.wall.QAndA.Answer({
			question_id: question_id,
			answer_id: answer_id
		});
		a.invalidQuestionID.subscribe(function(e, msg) {
			a.set_error_message(flag_form, msg);
		});
		var t = this;
		//execute flagging
		a.flag(flag_description, {
			success: function() {
				a.messaging.answer = 'Good Catch! Thanks for giving everyone the heads up.';
				a.messaging.answer_id = answer_id;
				a.answer_id = answer_id;
				ScFlagQandA('A', 'add', a.answer_id);

				//Hide the "view image" link
				a.obj.display = 'none';
				//update carousel
				t.update_carousel_after_flag();
				//old flag form present, remove it
				flag_form.parentNode.removeChild(flag_form);
				//set the same flagged content on the wall
				//flag_form.innerHTML = "";
				$('question_' + a.obj.question_id ).innerHTML = a.html();

			},
			failure: function(o, e) {
				if (o.status != -1) {
					var error = t.messages.answer.unflag.ERR_UNKNOWN;
					if (e) {
						error += ":\n" + e.message;
					}
					ajax_error(o, error, 'flag_carousel_answer_submit_onclick');
				}
            },
            error: function(o) {
                var msg = t.messages.answer.flag.ERR_UNKNOWN;
                if(o){
					msg += ":\n" + o.errorMessage;
				}
				t.set_error_message(flag_panel, msg);
            }

		});
		
	}, 
	// Pops open the "flag answer" dialog
	flag_answer_onclick: function(el, question_id) {
		var ans_el = this._getParentElement(el, 'answer');
		var answer_id = ans_el.id.split('_')[1];

		var t = TrimPath.processDOMTemplate("template_flag_content", { 
			content_type: 'answer',
			content_id: answer_id,
			question_id: question_id,
			is_from_carousel: false
		});

		var id = FLAG_ANSWER_ID_PREFIX + question_id;
		var r_el = $(id);
		if ( !r_el ) {
			// If the edit answer dialog exists, remove it
			this._remove_dialog(ans_el);

			r_el = this._create_dialog(t);
			r_el.id = id;
			ans_el.appendChild(r_el);
		}
	},

	unflag_answer_onclick: function(el, question_id, answer_id) {
		var ans_el = this._getParentElement(el, 'answer');
		var a = new BCNTRY.wall.QAndA.Answer({
			question_id: question_id,
			answer_id: answer_id,
			association: $('association').value
		});
		var container = this._getParentElement(ans_el, 'QandA');

		a.invalidQuestionID.subscribe(function(e, msg) {
			a.set_error_message(qanda_el, msg);
		});

		var p = this;

		a.unflag({
			success: function(o) {
				a.messaging.answer = 'Unflagged answer successfully.';
				a.messaging.answer_id = answer_id;
				container.innerHTML = a.html();
				p.add_miniprofile_listeners(container);
				ScFlagQandA('A', 'remove', a.answer_id);
			},
			failure: function(o, e) {
				if (o.status != -1) {
					var error = 'There was an error unflagging the answer';
					if (e) {
						error += ":\n" + e.message;
					}
					ajax_error(o, error, 'unflag_answer_onclick');
				}
			},
			error: function(o) {
				a.set_error_message(ans_el, o.errorMessage);
			}
		});

	},

	// Compares two html strings to see if they match
	_compare_html: function(one, two) {
		one = one.replace(/<\/?[a-zA-Z"'() ]+>/g, '');
		two = two.replace(/<\/?[a-zA-Z"'() ]+>/g, '');
		return (one === two);
	},

	flag_answer_submit_onclick: function(flag_form) {

		var container = this._getParentElement(flag_form, 'QandA');

		// If they supplied flags, then they actually want the answer flagged
		var a;
		a = new BCNTRY.wall.QAndA.Answer ({
			question_id: flag_form.question_id.value,
			answer_id: flag_form.answer_id.value,
			association: $('association').value
		});
		a.invalidQuestionID.subscribe(function(e, msg) {
			a.set_error_message(flag_form, msg);
		});

		var p = this;

		a.flag( flag_form.flag_description.value, {
			success: function() {
				a.messaging.answer = 'Good Catch! Thanks for giving everyone the heads up.';
				a.messaging.answer_id = a.obj.answer.answer_id;
			   
				container.innerHTML = a.html();

				p.add_miniprofile_listeners(container);
				ScFlagQandA('A', 'add', a.obj.answer.answer_id);
				//update carousel
				if(a.obj.answer.image_url_small) {
					var current_item_array;
					var current_index = -1;
					if( BCNTRY.pdp_images.mode()  != BCNTRY.pdp_images.customer_product_images ){
						current_item_array = BCNTRY.pdp_images.mode();
						current_index = BCNTRY.pdp_images.current;
					}
					//set the flagged content as current in the carousel, then remove it
					if( BCNTRY.customer_product_images.set_current_in_carousel_by_id( a.obj.answer.answer_id ) )
						//remove the content photo from the carousel
						p.update_carousel_after_flag();
					//if the original carousel was other than the gear/content photos, restore it. 
					if(current_index != -1)
						BCNTRY.pdp_images.set_current(current_item_array , current_index);
				}
			},
			failure: function(o, e) {
				if (o.status != -1) {
					var error = 'There was an error flagging the answer';
				if (e) {
						error += ":\n" + e.message;
					}
					ajax_error(o, error, 'flag_answer_submit_onclick');
				}
			},
			error: function(o) {
				a.set_error_message(flag_form, o.errorMessage);
			}
		});
	},

	//Saves the selected flags for a given question from the carousel
	flag_carousel_question_submit_onclick: function( flag_form ){
		//allow just one connection at a time
		if (BCNTRY.wall.connection) { return }
		//make the form unique
		flag_form.id = 'flag_form_' + flag_form.question_id.value;
		var flag_panel = this._getParentElement(flag_form, 'flag_container');
		//get the flagging data
		var flag_description = flag_form.flag_description.value;
		var q = new BCNTRY.wall.QAndA.Question({
			question_id: flag_form.question_id.value
		});
		var t = this;
		//execute flagging
		q.flag(flag_description, {
			success: function() {
				q.messaging.question = 'Good Catch! Thanks for giving everyone the heads up.';
				//Hide the "view image" link
				q.obj.display = 'none';
				//update carousel
				t.update_carousel_after_flag();
				//flag_form.innerHTML = "";// q.html(); 
				//old flag form present, remove it
				flag_form.parentNode.removeChild(flag_form);

				//set the same flagged content on the wall
				q.obj.display = 'flagged';
				$('question_' + q.obj.question_id).innerHTML = q.html();

			},
			failure: function(o, e) {
				if (o.status != -1) {
					var error = 'There was an error flagging the question';
					if (e) {
						error += ":\n" + e.message;
					}
					ajax_error(o, error, 'flag_carousel_question_submit_onclick');
				}
            },
            error: function(o) {
                var msg = 'There was an error flagging the question'; 
				if(o){
					msg += ":\n" + o.errorMessage;
				}
				t.set_error_message(flag_panel, msg);
            }

		});
		
	}, 
	// Pops open the "Flag question" dialog
	flag_question_onclick: function(el, question_id) {
		var question_el = this._getParentElement(el, 'question');
		var t = TrimPath.processDOMTemplate("template_flag_content", { 
			content_type: 'question',
			content_id: question_id,
			is_from_carousel: false
		});

		var id = FLAG_QUESTION_ID_PREFIX + question_id;
		var r_el = $(id);
		if (!r_el) {
			// If the edit question dialog exists, remove it
			this._remove_dialog(question_el);

			r_el = this._create_dialog(t);
			r_el.id = id;
			question_el.appendChild(r_el);
		}
	},

	flag_question_submit_onclick: function(flag_form) {
		var q = new BCNTRY.wall.QAndA.Question({
			question_id: flag_form.question_id.value
		});
		var container = this._getParentElement(flag_form, 'QandA');
		var flag_description = flag_form.flag_description.value;
	
		q.invalidQuestionID.subscribe(function(e, msg) {
			a.set_error_message(flag_form, msg);
		});

		var p = this;

		q.flag( flag_description, {
			success: function(o) {
				q.messaging.question = 'Good Catch! Thanks for giving everyone the heads up.';
				container.innerHTML = q.html();
				p.add_miniprofile_listeners(container);
				ScFlagQandA('Q', 'add', q.obj.question_id);
				//update carousel
				if(q.obj.image_url_small) {
					var current_item_array;
					var current_index = -1;
					if( BCNTRY.pdp_images.mode()  != BCNTRY.pdp_images.customer_product_images ){
						current_item_array = BCNTRY.pdp_images.mode();
						current_index = BCNTRY.pdp_images.current;
					}
					//set the flagged content as current in the carousel, then remove it
					if( BCNTRY.customer_product_images.set_current_in_carousel_by_id(q.obj.question_id) )
						//remove the content photo from the carousel
						p.update_carousel_after_flag();
					//If this question has answers with photos, remove them from the carusel as well
					for(var i=0; i < q.obj.answers.length; i++) {
						var a = q.obj.answers[i];
						if( BCNTRY.customer_product_images.set_current_in_carousel_by_id(a.answer_id) )
								p.update_carousel_after_flag();
					}
					//if the original carousel was other than the gear/content photos, restore it. 
					if(current_index != -1)
						BCNTRY.pdp_images.set_current(current_item_array , current_index);
				}

			},
			failure: function(o, e) {
				if (o.status != -1) {
					var error = 'There was an error flagging the question';
					if (e) {
						error += ":\n" + e.message;
					}
					ajax_error(o, error, 'flag_question_submit_onclick');
				}
			},
			error: function(o) {
				q.set_error_message(flag_form, o.errorMessage);
			}
		});
	},

	unflag_question_onclick: function(el, question_id) {
		var quest_el = this._getParentElement(el, 'question');
		var q = new BCNTRY.wall.QAndA.Question({
			question_id: question_id
		});
		var container = this._getParentElement(quest_el, 'QandA');

		q.invalidQuestionID.subscribe(function(e, msg) {
			q.set_error_message(quest_el, msg);
		});

		var p = this;

		q.unflag({
			success: function(o) {
				q.messaging.question = "Unflagged question successfully";
				container.innerHTML = q.html();
				p.add_miniprofile_listeners(container);
				ScFlagQandA('Q', 'remove', q.obj.question_id);
			},
			failure: function(o, e) {
				if (o.status != -1) {
					var error = 'There was an error unflagging the question';
					if (e) {
						error += ":\n" + e.message;
					}
					ajax_error(o, error, 'unflag_question_onclick');
				}
			},
			error: function(o) {
				q.set_error_message(quest_el, o.errorMessage);
			}
		});

	},

	//removes the flagged image from the carousel	
	update_carousel_after_flag: function(){
		//save the flagged cpi index
		var flagged_cpi = BCNTRY.pdp_images.current;
		//Display a different photo 
		if( BCNTRY.pdp_images.displayed_items() == 1 ){
			//The flagged cpi was the last one

			//hide the cpi shadowed bar
			yd.addClass( $('cpi_views'), 'hidden_content' );
			//show the empty 3rd row in carousel
			yd.removeClass( $('cpi_views_empty'), 'hidden_content');

			//show the main swatch picture
			if( get_number_swatch_items() > 0 ) {
				BCNTRY.pdp_images.set_current( BCNTRY.pdp_images.swatches, 0 );
				BCNTRY.pdp_images.load_large_image();
			}
		}
		else if( BCNTRY.pdp_images.current == BCNTRY.pdp_images.mode().length -1 ){
			//this is the last image, go to the previous
			 BCNTRY.pdp_images.previous();
		}
		else {
			//this is the first cpi, go to the next
			BCNTRY.pdp_images.next();
		}
		//remove the flagged image from the display list
		var carousel_li_name = 'cpi_carousel-item-' + ( flagged_cpi + 1 );
		$('cpi_carousel_list').removeChild ( $(carousel_li_name) );
		BCNTRY.pdp_images.removed_items++;
	
		//display the flgged cpi message and fix the images counter
		//flag_form.innerHTML = TrimPath.processDOMTemplate(template_name , content_obj );
		$('cpi_views_title_count').innerHTML = BCNTRY.pdp_images.displayed_items();
		if( $('cpi_carousel_list').childNodes.length == 1 ){
			yd.addClass( $('cpi_views_title_s'), 'hidden_content' );
		}
		
	},

	//Saves the selected flags for a given review from the carousel
	flag_carousel_review_submit_onclick: function( flag_form ){
		//allow just one connection at a time
		if (BCNTRY.wall.connection) { return }
		//make the form unique
		flag_form.id = 'flag_form_' + flag_form.review_id.value;
		var flag_panel = this._getParentElement(flag_form, 'flag_container');
		//get the flagging data
		var flag_description = flag_form.flag_description.value;
		var r = new BCNTRY.wall.Review({
			review_id: flag_form.review_id.value
		});
		var t = this;
		//execute flagging
		r.flag(flag_description, {
			success: function() {
				r.obj.message = t.messages.review.flag.SUCCESS;
				//Hide the "view image" link
				r.obj.display = 'none';
				//update carousel
				t.update_carousel_after_flag();

				//flag_form.innerHTML = r.html(); 
				//old flag form present, remove it
				flag_form.parentNode.removeChild(flag_form);
				
				//set the same flagged content on the wall
				r.obj.display = 'flagged';
				$('review_' + r.obj.review_id).innerHTML = r.html();

			},
			failure: function(o, e) {
				if (o.status != -1) {
					var error = t.messages.review.unflag.ERR_UNKNOWN;
					if (e) {
						error += ":\n" + e.message;
					}
					ajax_error(o, error, 'flag_carousel_review_submit_onclick');
				}
            },
            error: function(o) {
                var msg = t.messages.review.flag.ERR_UNKNOWN;
                if(o){
					msg += ":\n" + o.errorMessage;
				}
				t.set_error_message(flag_panel, msg);
            }

		});
		
	}, 

	// Pops open the "flag review" dialog
	flag_review_onclick: function(el, review_id) {
		var review_el = this._getParentElement(el, 'review_item');
		if(!review_el )
			alert('missing review_item element');

		var t = TrimPath.processDOMTemplate("template_flag_content", {
			content_type: 'review',
			content_id: review_id,
			is_from_carousel: false
		});
		var id = FLAG_REVIEW_ID_PREFIX + review_id;
		var r_el = $(id);
		if ( !r_el ) {
			// If the edit review dialog exists, remove it
			this._remove_dialog(review_el);

			r_el = this._create_dialog(t);
			r_el.id = id;
			review_el.appendChild(r_el);
		}
	},

	flag_review_submit_onclick: function(flag_form) {
		var r = new BCNTRY.wall.Review({
			review_id: flag_form.review_id.value
		});
		
		var container = this._getParentElement(flag_form, 'review');
		var flag_description = (flag_form.flag_description.value).replace(/^\s+|\s+$/gi,'');//Trim description

		r.invalidReviewID.subscribe(function(e, msg) {
			r.set_error_message(flag_form, msg);
		});

		var p = this;

		r.flag( flag_description, {
			success: function(o) {
				r.obj.message = p.messages.review.flag.SUCCESS;
				container.innerHTML = r.html();
				p.add_miniprofile_listeners(container);
				ScFlagQandA('R', 'add', r.obj.review_id);
				//update carousel
				if(r.obj.image_url_small) {
					var current_item_array;
					var current_index = -1;
					if( BCNTRY.pdp_images.mode()  != BCNTRY.pdp_images.customer_product_images ){
						current_item_array = BCNTRY.pdp_images.mode();
						current_index = BCNTRY.pdp_images.current;
					}
					//set the flagged content as current in the carousel, then remove it
					if( BCNTRY.customer_product_images.set_current_in_carousel_by_id(r.obj.review_id) ){
						//remove the content photo from the carousel
						p.update_carousel_after_flag();
					}
					//if the original carousel was other than the gear/content photos, restore it. 
					if(current_index != -1)
						BCNTRY.pdp_images.set_current(current_item_array , current_index);
				}
			},
			failure: function(o, e) {
				if (o.status != -1) {
					var error = p.messages.review.unflag.ERR_UNKNOWN;
					if (e) {
						error += ":\n" + e.message;
					}
					ajax_error(o, error, 'flag_review_submit_onclick');
				}
			},
			error: function(o) {
				r.set_error_message(flag_form, o.errorMessage);
			}
		});
	},

	// Unflags flagged reviews
	unflag_review_onclick: function(el, review_id) {
		if (BCNTRY.wall.connection) { return }
			var container = this._getParentElement(el, 'review');
		var review = new BCNTRY.wall.Review({ review_id: review_id });
		var t = this;
		review.unflag({
			success: function(a) {
					review.obj.message = t.messages.review.unflag.SUCCESS;
				    container.innerHTML = review.html();	
				},
			failure: function(o, e) {
					var error = t.messages.review.unflag.ERR_UNKNOWN;
					if (e) {
						error += ":\n" + e.message;
					}
					ajax_error(o, error, 'unflag_review_onclick');
				},
			error: function(o) {
					var msg = t.messages.review.unflag.ERR_UNKNOWN;
					if (o.attributes.failure_type == 'TOO_MANY') {
					    msg = t.messages.review.unflag.ERR_TOO_MANY;
                    }
                    t.set_error_message(container, msg);
			}
		});
	},

	//METHODS FOR FLAFGING COMMENTS BEGIN

	// Pops open the "flag comment" dialog
	flag_comment_onclick: function(el, comment_id) {
		var comment_el = this._getParentElement(el, 'comment threaded');
		var comment_id = comment_el.id.split('_')[1];

		var t = TrimPath.processDOMTemplate("template_flag_content", {
			content_type: 'comment',
			comment_id: comment_id,
			is_from_carousel: false
		});

		var id = FLAG_COMMENT_ID_PREFIX + comment_id;
		var r_el = $(id);
		if ( !r_el ) {
			// If the edit comment diaglog  exists, remove it
			this._remove_dialog(comment_el);

			r_el = this._create_dialog(t);
			r_el.id = id;
			comment_el.appendChild(r_el);
		}
	},

	flag_comment_submit_onclick: function(flag_form) {
		var c = new BCNTRY.wall.Comment({
			id: flag_form.comment_id.value
		});

		var container = this._getParentElement(flag_form, 'comment threaded');
		var flag_description = (flag_form.flag_description.value).replace(/^\s+|\s+$/gi,'');//Trim description

		//c.invalidCommentID.subscribe(function(e, msg) {
			//c.set_error_message(flag_form, msg);
		//});

		var p = this;

		c.flag( flag_description, {
			success: function(o) {
				c.message = p.messages.comment.flag.SUCCESS;
				c.obj.display = 'flagged';
				container.innerHTML = c.html();
				p.add_miniprofile_listeners(container);
			},
			failure: function(o, e) {
				if (o.status != -1) {
					var error = p.messages.comment.flag.ERR_UNKNOWN;
					if (e) {
						error += ":\n" + e.message;
					}
					ajax_error(o, error, 'flag_comment_submit_onclick');
				}
			},
			error: function(o) {
				c.set_error_message(flag_form, o.errorMessage);
			}
		});
	},

	// Unflags flagged comments
	unflag_comment_onclick: function(el, comment_id) {
		if (BCNTRY.wall.connection) { return }
		var container = this._getParentElement(el, 'comment threaded');
		var comment = new BCNTRY.wall.Comment({ id: comment_id });
		var t = this;
		comment.unflag({
			success: function(a) {
					comment.message = t.messages.comment.unflag.SUCCESS;
					container.innerHTML = comment.html();
				},
			failure: function(o, e) {
					var error = t.messages.comment.unflag.ERR_UNKNOWN;
					if (e) {
						error += ":\n" + e.message;
					}
					ajax_error(o, error, 'unflag_comment_onclick');
				},
			error: function(o) {
					t.set_error_message(container, o.errorMessage);
			}
		});
	},

	//COMMENTS END
	
	view_flagged_question_onclick: function(in_el, question_id) {
		var qanda_el = this._getParentElement(in_el, 'QandA');
		var q = new BCNTRY.wall.QAndA.Question({
			question_id: question_id
		});
		var p = this;
		q.load(function(o) {
			q.obj.display = 'normal';
			qanda_el.innerHTML = q.html();
			p.add_miniprofile_listeners(qanda_el);
		});
	},

   	view_flagged_answer_onclick: function(in_el, question_id, answer_id) {
		var qanda_el = this._getParentElement(in_el, 'QandA');
		var q = new BCNTRY.wall.QAndA.Question({
			question_id: question_id
		});
		var p = this;
		q.load(function(o) {
			// Loop through answers and specify which one we want to see
			q.obj.display = 'normal';
			for(var i=0; i < q.obj.answers.length; i++) {
				var a = q.obj.answers[i];
				if (a.answer_id == answer_id) {
					a.display = 'normal';
				}
			}
			qanda_el.innerHTML = q.html();
			p.add_miniprofile_listeners(qanda_el);
		});
	},

	view_flagged_review_onclick: function(in_el, review_id) {
		var review_el = this._getParentElement(in_el, 'review');
		var r = new BCNTRY.wall.Review({
			review_id: review_id
		});
		var p = this;
		r.load(function(o) {
			r.obj.display = 'normal';
			review_el.innerHTML = r.html();
			p.add_miniprofile_listeners(review_el);
		});
	},

	view_flagged_comment_onclick: function(in_el, comment_id) {
		var comment_el = this._getParentElement(in_el, 'comment threaded');
		var c = new BCNTRY.wall.Comment({ id: comment_id });
		var p = this;
		c.load({
			success: function(o) {
				c.obj.comment.display = 'normal';
				comment_el.innerHTML = c.html();
				p.add_miniprofile_listeners(comment_el);
			},
			failure: function(o, e) {
				alert('Viewing flagged comment failed due to a communication error.');
			},
			error: function(o) {
				alert('Viewing flagged comment failed.');
			}
		});
	},
	// Shows the "Edit question" dialog
	edit_question_onclick: function(el, question_id) {
		var question_el = this._getParentElement(el, 'question');
		var body = this._filter_qanda_html($('question_' + question_id + '_body').value);
		var img_url = $('question_' + question_id + '_img_url').value;

		var t = TrimPath.processDOMTemplate("qanda_edit_question", { 
			question_id: question_id,
			sku: $('association').value,
			content: body,
			img_el: (img_url.length > 0)
				? '<img class="content_image" src="' + img_url + '" />'
				: undefined
		});

		var id = EDIT_QUESTION_ID_PREFIX + question_id;
		var r_el = $(id);
		if ( !r_el ) {
			// If the flag question dialog exists, remove it
			this._remove_dialog(question_el);

			r_el = this._create_dialog(t);
			r_el.id = id;
			question_el.appendChild(r_el);
		}
		var form = yd.getFirstChildBy( r_el, function(o) {  return (o.tagName.toUpperCase() === 'FORM'); });
		var output_el = this._getChildElement(form, "question_chars");
		BCNTRY.wall.PDP._number_question_characters(form.question_content, output_el, 1000);
	},

	toggle_edit_content_photo_onclick: function(src_el) {
		var container = this._getParentElement(src_el, 'content_image_upload_container');
		var action_container = this._getChildElement(container, 'action_container');
		var input_container = this._getChildElement(container, 'input_container');
		if(yd.getStyle(input_container, 'display') == 'none') {
			yd.setStyle(action_container, 'display', 'none');
			yd.setStyle(input_container, 'display', 'block');
		}
		else {
			yd.setStyle(action_container, 'display', 'block');
			yd.setStyle(input_container, 'display', 'none');
		}
	},

	delete_content_photo_onclick: function(src_el) {
		var container = this._getParentElement(src_el, 'content_image_upload_container');
		var delete_input = this._getChildElement(container, 'delete_cust_image');
		var img_el = this._getChildElement(container, 'content_image');
		var deleted_message = this._getChildElement(container, 'deleted_message');
		yd.getElementsByClassName(
			'collapsed',
			undefined,
			container,
			function(el) { yd.removeClass(el, 'collapsed') }
		);
		img_el.parentNode.removeChild(img_el);
		delete_input.value = '1';
		yd.setStyle(deleted_message, 'display', 'block');
		BCNTRY.wall.PDP.toggle_edit_content_photo_onclick(src_el);
	},

	question_content_onkeyup: function(form) {
		var output_el = this._getChildElement(form, "question_chars");
		BCNTRY.wall.PDP._number_question_characters(form.question_content, output_el, 1000);
	},

	answer_content_onkeyup: function(form) {
//		var output_el = this._getChildElement(form, "answer_chars");
//		BCNTRY.wall.PDP._number_question_characters(form.answer_content, output_el, 5000);
	},
	
	comment_content_onkeyup: function(form) {
	//TODO: review if this is needed
	},

	_number_question_characters: function(textarea, output_el, chars) {
		var chars_left = chars - textarea.value.length;
			
		if (chars_left <= 0) {
			textarea.value = textarea.value.substr(0, chars);
			chars_left = 0;
		}
		if (chars_left <= 100) {
			output_el.innerHTML = chars_left + (chars_left === 1 ? ' character' : ' characters') + " left";
		}
		else {
			output_el.innerHTML = "";
		}
	},

	answer_content_onfocus: function(form_el) {
		yd.addClass(form_el, 'solicit_expanded');
		if (form_el.answer_content.value === form_el.answer_content_default.value) {
			form_el.answer_content.value = '';
		}
	},
	
	comment_content_onfocus: function(form_el) {
		yd.addClass(form_el, 'solicit_expanded');
		if (form_el.comment_content.value === form_el.comment_content_default.value) {
			form_el.comment_content.value = '';
		}
	},

	question_content_onfocus: function(form_el) {
		yd.addClass(form_el, 'solicit_expanded');
		if (form_el.question_content.value === form_el.question_content_default.value) {
			form_el.question_content.value = '';
		}
	},

	show_full_review_onclick: function(el, review_id) {
		var container = this._getParentElement(el, 'review');
		var r = new BCNTRY.wall.Review({
			review_id: review_id
		});
		var p = this;
		r.load(function() {
			container.innerHTML = r.html();
			p.add_miniprofile_listeners(container);
		});
	}
};

})();

BCNTRY.add_to_gear_list_form_onsubmit = function(f) {
    try{
    var flypage_el = document.getElementById("flypage");
    var qty_el     = document.getElementById("mv_order_quantity");

    if (qty_el) {
        var qty = qty_el.value;
        if (qty.match(/^\d+$/)) 
            f.quantity.value = qty;
    }
    if (flypage_el) {
        var variant = flypage_el.mv_sku.value;
        f.variant_sku.value = variant;
    }

    // "Create new gear list" is selected
    if ( !menuGearLists.activeItem || menuGearLists.activeItem.value == '') {
		ScTrackAddToGearListClicked(false, true, true);
        return true;
    }
    var params = {
        'listId' : menuGearLists.activeItem.value,
        'variant_sku' : f.variant_sku.value,
        'quantity'    : f.quantity.value,
        'sku'    : f.sku.value
    };

    asyncRequest('/'+BCNTRY.site.catalog+'/gearlist/rest/add_item_to_list', {
            success: function(data) {
                $('list_success_message').innerHTML = '<b>This product has been added to your <a href="'+data.list_url+'">'+data.list_name_truncated+'</b></a>';
                yd.removeClass('list_success_message', 'none');
                setTimeout(function() { 
                    var fadeOut = new YAHOO.util.Anim('list_success_message', { opacity: { to: 0 } }, 0.5);
                    fadeOut.onComplete.subscribe(function() {
                        yd.addClass('list_success_message', 'none');
                        yd.setStyle('list_success_message', 'opacity', 1);
                    });
                    fadeOut.animate();
                }, 4000);
            },
            error: function(o, e) {
                alert(o.errorMessage +' '+e);
            },
            failure: function(o,e) {
                alert("There was a problem adding the item to the list.  Please try again."+e);
            }
        }, params
    );

    // Submit
    }catch(e){
		if(console)
	        console.log("error: "+e.message);
    }
    return false;
}
var menuGearLists;

BCNTRY.init_dropdown_gearlists = function() {
	var button = new YAHOO.widget.Button(
		"dropdown_gearlists", 
		{
			type: "menu",
			menu: document.getElementById("listId") 
		}
	);
	//	Click event listener for the Button's Menu instance
    var form_submitted = false;
	var onMenuClick = function (p_sType, p_aArgs, p_bButton) {

		var oEvent = p_aArgs[0],	//	DOM event
		oMenuItem = p_aArgs[1];	//	MenuItem instance that was the target of the event
		if (oMenuItem) {
			var text = oMenuItem.cfg.getProperty("text");
			YAHOO.log("[MenuItem Properties] text: " + text + ", value: " + oMenuItem.value);
			p_bButton.set("label", ("<em class=\"yui-button-label\">" + oMenuItem.cfg.getProperty("text") + "</em>"));
		}
        var form = document.add_to_gear_list_form;
        var needs_submit = BCNTRY.add_to_gear_list_form_onsubmit(form);
        if (needs_submit && !form_submitted) {
            ScTrackAddToGearListClicked(true, false, form.is_logged_in.value == 1);
            form_submitted = true;
            form.submit();
        }
	};

	//	Add a "click" event listener for the Button's Menu
	menuGearLists = button.getMenu();
	menuGearLists.subscribe("click", onMenuClick, button );

//	menuGearLists.subscribe("click", ScTrackPDPGearListSelectChanged);
}

ye.onDOMReady(function() {
	// run function on page load finish to clean up cookies for content that
	// still needs to be posted from QandA and reviews.
	var cookie_content = _readCookie('content_to_post');

    var gift_box_dialog;
    ye.on("gift_box_more_info", "click", function(evt) {
        try{
// Instantiate the Dialog
        if (!gift_box_dialog) {
            var gfd = $("gift_box_dialog");
            gfd.parentNode.removeChild(gfd);
            document.body.appendChild(gfd);
            gift_box_dialog = new YAHOO.widget.Dialog("gift_box_dialog", 
                {fixedcenter : true,
                visible : false, 
                constraintoviewport : true,
                close: true,
                draggable: false,
                strings: { 'close' : 'Closa' },
                modal: true
                } );
            yd.getElementsByClassName("continue_shopping", "a", "gift_box_dialog", function(el){ ye.on(el, "click", function(evt){ gift_box_dialog.hide(); ye.stopEvent(evt); }) });
            yd.getElementsByClassName("btn_close", "a", "gift_box_dialog", function(el){ ye.on(el, "click", function(evt){ gift_box_dialog.hide(); ye.stopEvent(evt); }) });
            gift_box_dialog.render();
        }
        gift_box_dialog.show();
        ye.stopEvent(evt);
        } catch(e){ alert(e.message) }
    });

	if (cookie_content) {
		if (window.location.href.match('user')) {
			//keep cookie
			//nothing to do here for now
		}
		else {
			//server should have already processed cookie,
			//or cookie isn't needed anymore
			_deleteCookie('content_to_post', '/');
		}
	}

	var cookie_event = _readCookie('fire_event');
	if (cookie_event) {
		var result = cookie_event.split('_');
		if (result[0] == 'Q' || result[0] == 'A') {
			if (result[1] == 'new' || result[1] == 'edit') {
				ScSubmitQandA(result[0], result[1]);
			}
		}
		else if (result[0] == 'R') {
			location.hash = 'reviews';
			ScSubmitReview(result[1]);
		}
		_deleteCookie('fire_event', '/');
	}

	// QAndA actions
	if (window.location.hash.match('action=')) {
		var action = window.location.hash.split('=')[1];
		if (action) {
			var qid = action.split('_')[1];
			if (qid) {
				var gce = BCNTRY.wall.PDP._getChildElement;
				var q_el = $('question_' + qid);
				var qobj = gce(q_el, 'question');
				var aobj = gce(q_el, 'answer');

				BCNTRY.pdp.switchTab('qanda_tab');

				if (action.match('answer') && aobj) {
					var opt = gce(aobj, 'answer_options');
					if (opt) {
						var improveobj = gce(opt, 'improve_link');
						if (improveobj) {
							BCNTRY.wall.PDP.improve_answer_onclick(improveobj, qid);
						}
					}
				}
				else if (action.match('flag') && qobj) {
					var opt = gce(qobj, 'question_options');
					if (opt) {
						var flagobj = gce(opt, 'flag_link');
						if (flagobj) {
							BCNTRY.wall.PDP.flag_question_onclick(flagobj, qid);
						}
					}
				}
				var coords = yd.getXY(q_el);
				window.scrollTo( coords[0], coords[1] );
			}
		}
	}
});

//Price Comparison logic

//Request price comparison data from the servlet
function price_compare_init(){
    var callback = 'price_compare_display';
    var sku = document.getElementById('price_compare_sku').value;
    var title = escape(document.getElementById('price_compare_title').value);

    var objTransaction = YAHOO.util.Get.script("http://j.backcountry.com/PriceCompareWeb/pricecompare?sku="+sku+"&format=JS&callback="+callback+"&title="+title, {
      onSuccess: function(o) {
      },
      onFailure: function(o) {
        if(console)
          console.log("Error on pricecomparison call " + o);
      },
      onTimeout: function() {
        if(console)
          console.log("Timeout on pricecomparison call");
      }
    });
};

//Geardigger vendor click event, records omniture event
function price_compare_click(sku, vendor, obj) {
  var s_sc;
  try {
    //from SiteCatalystUtils
    clearVars();
    s_sc = s_gi(sc_account);
    //if we got to this point, assume omniture code has been loaded
  }
  catch (err) {
    if(console)
      console.log("Omniture client code not present, (no tracking) error was"+err);
  }

    try {
        s_sc.events = 'event68,event69';
        s_sc.products = ';' + sku + ';;;event69=.25';
        s_sc.prop16 = vendor;
        s_sc.eVar48 = "Return from competitor";
        s_sc.linkTrackVars = 'prop16,eVar48,events,products';
        s_sc.linkTrackEvents = 'event68,event69';

        //Prevent event double counting
        var lt=obj.href!=null?s_sc.lt(obj.href):"";
        if (lt=="") {
          s_sc.tl(obj,'o','Click Geardigger Link');
        }

    } catch(error) {
      if(console)
        console.log(error);
    }
    return true;
};

//Displays the price compare 
//  Template must be set on site.js to price_compare_template
function price_compare_display(json_data){
     var promo_well = document.getElementById('promo_price_compare');
       if(json_data.products != null && json_data.products.length > 0) {
         var parsedTemplate = TrimPath.parseTemplate(price_compare_template);
         var html_data = parsedTemplate.process(json_data);
         promo_well.innerHTML = html_data;

		 //Send event to omniture
         var s_sc;
         try {
           //from SiteCatalystUtils
           clearVars();
           s_sc = s_gi(sc_account);
           //if we got to this point, assume omniture code has been loaded
         }
         catch (err) {
           if (console)
             console.log("Omniture client code not present, (no tracking) error was"+err);
         }

         try {
           s_sc.events = 'event67';
           s_sc.linkTrackVars = 'events,products';
           s_sc.linkTrackEvents = 'event67';
           s_sc.products = ';' + json_data.sku + ';;;;;';
           s_sc.tl(this,'o',s_sc.pageName);
         }
         catch (err) {
           if(console)
             console.log("Sending to omniture error " + err);
         }

       }
}
YAHOO.util.Event.onDOMReady(function() {
  try {
    //display price_compare only if price compare promo tag is available
    if($('promo_price_compare')){
        price_compare_init();
    }
  }
  catch(error) {
    if(console)
      console.log(error);
  }
});


// highslide config
hs.graphicsDir = '/js/global/highslide/graphics/';
hs.numberOfImagesToPreload = 0;
hs.showCredits = false;
hs.outlineType = 'rounded-white';
hs.dimmingOpacity = 0.5;
hs.align = 'center';
hs.loadingText = 'Loading... (click to cancel)';
hs.restoreTitle = 'Click to close image, click and drag to move.';
hs.registerOverlay({
        overlayId: 'highslide-closebutton',
            position: 'top right',
                fade: 2 // fading the semi-transparent overlay looks bad in IE
});

