/*Copied from /struts/CommonFunctions.js Start */


/**
 *      Methods for the tabbed component
 */
var unselectedClass = "tab_default tab_unselected";
var unselectedContentsClass = "tab_contents_hidden";
var unselectedOverClass = "tab_default tab_unselected tab_unselected_over";
var selectedClass = "tab_default tab_selected";
var selectedContentsClass = "tab_contents_header";
var prettyUrlExtension=".html";
var pageTracker = null;
var setIntervalHolder;


var EmbedProduct = {
    overlayElement: "embedonblog_overlay",
    callerElement : "embed_caller",
    productIdElement : "hdnProductId",
    imageElementId : "imgProduct",
    heightElementId : "tbxHeight",
    widthElementId : "tbxWidth",
    userNameElementId : "user_name",
    codeElementId : "txt_code",
    domain : "http://www.wanelo.com/",
    ratio: 1,
    imageWidth: 0,
    imageHeight: 0,
    imagePath : "",
    userName : null,
    html: "",
    pId: 0,
    maxWidth : 0,
    maxHeight : 0,
    replaceCode : function(){
       
        this.html = "<div style='padding-bottom: 2px; line-height: 0px'><a href='" +
        this.domain + "product/" + this.pId + "' target='_blank'><img src='" + this.imagePath + "' border='0' width='" + $(this.widthElementId).value
        + "' height ='" + $(this.heightElementId).value + "'/></a></div><div style='float: left; padding-top: 0px; padding-bottom: 0px;'><p style='font-size: 16px; color: #737373;'>Posted to &nbsp; <a style='text-decoration: underline; font-size: 16px; color: #737373;' target='_blank' href='" + this.domain + "'>Wanelo</a>"; 
        if(this.userName != null){
        	this.html = this.html + " by <a style='text-decoration: underline; font-size: 16px; color: #737373;' href='" + this.domain + this.userName + "' target='_blank'>" + this.userName + "</a>"; 
        }
        this.html = this.html + "</p></div>";
        $(this.codeElementId).value = this.html;
       // document.getElementById(this.codeElementId).innerHTML = this.html;
    },
    init: function() {
        this.pId = $(this.productIdElement).value;
        var image = new Image();
        image.src = $(this.imageElementId).src;
        this.imageWidth = image.width;
        this.imageHeight = image.height;
        this.imagePath = image.src;
        this.maxWidth = image.width;
        this.maxHeight = image.height;
        if($(this.userNameElementId) != null){
	        this.userName = dojo.string.trim($(this.userNameElementId).innerHTML);
        }
        $(this.widthElementId).value = this.imageWidth;
        $(this.heightElementId).value = this.imageHeight;
        this.ratio = parseFloat(this.imageWidth) / parseFloat(this.imageHeight);
        this.replaceCode();
        $(this.heightElementId).onkeyup = function(e){
        	EmbedProduct.sync(e, 'height');
        };
        $(this.widthElementId).onkeyup = function(e) {
        	EmbedProduct.sync(e, 'width');
        };
        $(this.codeElementId).onclick = function (e){
        	$(EmbedProduct.codeElementId).select();
        };
    },
   
    show: function(){
        this.init();
    	ActionCommons.showDiv(this.overlayElement); 
    },
    
    sync: function (e, tbxType){
    	//var evt = dojo.event.browser.fixEvent(e);
        if(tbxType == 'width'){
	    	var val = $(this.widthElementId).value;
	    	if(dojo.string.trim(val) == ''){
	    		$(this.heightElementId).value = 0;
	    	}else {
		    	if(!isNaN(val)){
			        if(parseInt(val) > this.maxWidth){
			        	$(this.widthElementId).value = this.maxWidth;
			            $(this.heightElementId).value = this.maxHeight;
			        }else {
			        	$(this.widthElementId).value = parseInt(val);
			        	$(this.heightElementId).value = parseInt(val / this.ratio);
			        }
	            }else {
	            	$(this.heightElementId).value = 'NaN';
	            }
	    	}
        }else if (tbxType == 'height'){
            var val = $(this.heightElementId).value;
            if(dojo.string.trim(val) == ''){
	    		$(this.widthElementId).value = 0;
	    	}else {
	            if(!isNaN(val)){
			        if(parseInt(val) > this.maxHeight){
			        	$(this.widthElementId).value = this.maxWidth;
			            $(this.heightElementId).value = this.maxHeight;
			        }else {
			        	$(this.widthElementId).value = parseInt(val * this.ratio);
			        	$(this.heightElementId).value = parseInt(val);
			        }
	            }else {
	            	$(this.widthElementId).value = 'NaN';
	            }
	    	}
        }
        this.replaceCode();
    }
   
};


function mouseIn(tab) {
    var className = tab.className;
    if (className.indexOf('unselected') > -1) {
        className = unselectedOverClass;
        tab.className = className;
    }
}

function mouseOut(tab) {
    var className = tab.className;
    if (className.indexOf('unselected') > -1) {
        className = unselectedClass;
        tab.className = className;
    }
}

/**
 * Checks whether the current form include an ajax-ified submit button, if so
 * we return true (otherwise false).
 *
 * @param form the HTML form element to check
 */
function isAjaxFormSubmit( form ) {
    // we check whether this exists
    //      <INPUT type="submit" dojoattachevent="onClick: execute" dojoattachpoint="attachBtn" />
    var thisForm = $(form.id);
    var matchUrl = /\s+dojoAttachPoint/;
    if( thisForm.innerHTML.match(matchUrl) ) {
        return false;
    }
    for( i=0; i<thisForm.elements.length; i++ ) {
        var field = thisForm.elements[i];
        if( field.type.toLowerCase()=='submit' ) {
            if( field.hasAttribute("dojoAttachPoint") && field.getAttribute("dojoAttachPoint")=="attachBtn" ) {
                return false;
            }
        }
    }
    return true;
}

/**  end tabbed component functions ******************************************************************/
/*Copied from /struts/CommonFunctions.js End */

function clearOptions (obj){
	while (obj.options.length > 0) {
   		obj.options[0] = null;
	}
}
function resetCategory() {
 if($('categorie_110001').onclick==null)
 {
 	$('categorie_110001').className='categories_name';
 	$('categorie_110001').onclick=function(e) {categoryChanged(110001);} 
 }else if($('categorie_110002').onclick==null){
 	$('categorie_110002').className='categories_name';
 	$('categorie_110002').onclick=function(e) {categoryChanged(110002);} 
 }else if($('categorie_110003').onclick==null){
 	$('categorie_110003').className='categories_name';
 	$('categorie_110003').onclick=function(e) {categoryChanged(110003);} 
 }else if($('categorie_110004').onclick==null){
 	$('categorie_110004').className='categories_name';
 	$('categorie_110004').onclick=function(e) {categoryChanged(110004);} 
 }else if($('categorie_110005').onclick==null){
 	$('categorie_110005').className='categories_name';
 	$('categorie_110005').onclick=function(e) {categoryChanged(110005);} 
 }else if($('categorie_110006').onclick==null){
 	$('categorie_110006').className='categories_name';
 	$('categorie_110006').onclick=function(e) {categoryChanged(110006);} 
 }
/* if($('checkUncategory').value==1)
 {
 	if($('categorie_110007').onclick==null){
 	$('categorie_110007').className='categories_name';
 	$('categorie_110007').onclick=function(e) {categoryChanged(110007);} 
 }
 }*/
}
function categoryChanged(obj){
	/*if(obj.selectedIndex > 0){
		$("categoryId").value = obj.options[obj.selectedIndex].value;
		var level = $("level");
		if(obj.id == 'category'){
			level.value = "1";
			executeAction('getChildren');
			$("categoryId").value = "";
		}else {
			level.value = "2";
			$("categoryId").value = obj.options[obj.selectedIndex].value;
		}
		//executeAction('getChildren');
	}else{
		$("categoryId").value = "";
		//remove all child objects
		var sel;
		if(obj.id == 'category'){
			sel = $("subCategory");
			clearOptions(sel);
			sel.options.add(new Option("--Select Subcategory--", "-1"));
		}
		
		sel = $("subSubCategory"); 
		if(sel){
			clearOptions(sel);
			sel.options.add(new Option("--Select Sub-sub-category--", "-1"));
		}
		
		
	}*/
	resetCategory();
	$("categoryId").value=obj;
	if($("pId").value>0 && $('cateId').value>0)
	{
		var id=$('cateId');
		$('categorie_'+id.value).className='categories_name';
	}
	$('categorie_'+obj).className='categories_name_current';
	$('categorie_'+obj).onclick = null;
}

function startTimer(){
	var v = setTimeout("keepAlive();", 5 * 60 * 1000); //first hit after 5 mins
}

function keepAlive(){
	setIntervalHolder = setInterval("executeAction('keepalive')", 5 * 60 * 1000); //subsequent hits after 5 mins
}

var emptyStarImage = new Image();
var fullStarImage = new Image();

function loadRatingImages()
{
	emptyStarImage.src = "/resources/images/star_empty.gif";
	fullStarImage.src = "/resources/images/star_full.gif";
}

function renderRatingImages (divId, rating, clickable, hiddenFieldId)
{

	var str = "";
	var imageTag;
	var anchorTag;
	var div;	
	
	div = ActionCommons.getElement(divId);
	div.innerHTML = "";
	for (var i = 1; i <= 5; i++)
	{
	    imageTag = document.createElement("img");
        imageTag.border = "0";
        imageTag.id = divId + "_img_" + i;
	    
	    if(i <= rating)
		{
			imageTag.src = fullStarImage.src;
		}
		else
		{
			imageTag.src = emptyStarImage.src;			
		}

        if(clickable)
		{
            anchorTag = document.createElement("A"); 
            anchorTag.href = "javascript:onRatingStarClicked(" + i + ", '" + divId +  "', '" + hiddenFieldId + "');";
            anchorTag.id = divId + "_a_" + i;
            div.appendChild(anchorTag);
	       	anchorTag.appendChild(imageTag);
	    }
		else
		{
	        div.appendChild(imageTag);
	    }
	}
	if(hiddenFieldId){
	    ActionCommons.getElement(hiddenFieldId).value = rating;
	}
}

function onRatingStarClicked (rating, divId, hiddenFieldId)
{
    var imgTag;
    for (var i = 1;i <= 5; i++)
	{
        imgTag = ActionCommons.getElement(divId + "_img_" + i);
        if(i <= rating)
		{
            imgTag.src = fullStarImage.src;
        }
		else
		{
            imgTag.src = emptyStarImage.src;
        }    
    }
	
    var field = ActionCommons.getElement(hiddenFieldId);
   	field.value = rating;
}

loadRatingImages();

function handler(widget, node){
	if(node){
		node.innerHTML = "";
		var fld = $("hdn_" + node.id);
		var clickable = $("clickable");
		if(fld){
			//alert(fld.value);
			renderRatingImages(node.id, fld.value, clickable, fld.id);
		}
		 
	}
}

function sliderHandler_all(widget, node)
{
	var min = ActionCommons.getElement("slider_all_minrange");
	var max = ActionCommons.getElement("slider_all_maxrange");
	min = Math.round(min.value);
	min = min - (min % 100);   			
		if (min < 0)
	{
		min = 0;
	}	

	max = Math.round(max.value);
	var remainder = max % 100;
	if(remainder > 0) 
	{
		max = (max - (max % 100)) + 100;
	}

	if(max > 0 && max > min)
	{
    	var span = ActionCommons.getElement("slider_all_minspan");
		span.innerHTML = "$" + min;
    	span = ActionCommons.getElement("slider_all_maxspan");
    	span.innerHTML = "$" + max;
	    
		var slider = new Control.Slider(['slider_all_leftknob','slider_all_rightknob'],'slider_all',{
	        sliderValue:[min, max],
	        restricted:true,
	        range:$R(min,max),
	        onSlide:onSliderSlide_all,
	        onChange:onSliderChange_all}
	  	);
  	}
	else 
	{
  		ActionCommons.hideDiv("slider_all_container", true);
  	}
}
  	
function onSliderSlide_all(v)
{
	$('slider_all_minspan').innerHTML= "$" + Math.round(v[0]);
	$('slider_all_maxspan').innerHTML= "$" + Math.round(v[1]);
}
  	
function onSliderChange_all (v)
{
	ActionCommons.getElement("minPrice_txt_all").value = Math.round(v[0]);
	ActionCommons.getElement("maxPrice_txt_all").value = Math.round(v[1]);
	$('slider_all_minspan').innerHTML="$" + Math.round(v[0]);
	$('slider_all_maxspan').innerHTML="$" + Math.round(v[1]);
	
	if(Math.round(v[1]) > 0)
	{
		var url = ActionCommons.getElement("slider_all_url");
		Controller.executeAction('searchpriceall', 'search_listing_all',url.value);
		//Controller.executeAction('searchpriceall', 'singleproductcategory_result',url.value);
	}	
}


function sliderHandler_fr(widget, node)
{
	var min = ActionCommons.getElement("slider_fr_minrange");
	var max = ActionCommons.getElement("slider_fr_maxrange");

	min = Math.round(min.value);	
	min = min - (min % 100);
	if (min < 0)
	{
		min = 0;
    }		

	max = Math.round(max.value);
	var remainder = max % 100;
	if(remainder > 0)
	{
		max = (max - (max % 100)) + 100;
	}

	if(max > 0 && max > min)
	{
    	var span = ActionCommons.getElement("slider_fr_minspan");
    	span.innerHTML = "$" + min;
    	span = ActionCommons.getElement("slider_fr_maxspan");
    	span.innerHTML = "$" + max;
	    
		var slider = new Control.Slider(['slider_fr_leftknob','slider_fr_rightknob'],'slider_fr',{
	        sliderValue:[min, max],
	        restricted:true,
	        range:$R(min,max),
	        onSlide:onSliderSlide_fr,
	        onChange:onSliderChange_fr}
	  	);
  	}
	else
	{
  		ActionCommons.hideDiv("slider_fr_container", true);
  	}
}
  	
function onSliderSlide_fr(v)
{
	$('slider_fr_minspan').innerHTML = "$" + Math.round(v[0]);
	$('slider_fr_maxspan').innerHTML = "$" + Math.round(v[1]);
}
  	
function onSliderChange_fr (v)
{
	ActionCommons.getElement("minPrice_txt_fr").value = Math.round(v[0]);
	ActionCommons.getElement("maxPrice_txt_fr").value = Math.round(v[1]);

	$('slider_fr_minspan').innerHTML="$" + Math.round(v[0]);
	$('slider_fr_maxspan').innerHTML="$" + Math.round(v[1]);	

	if(Math.round(v[1]) > 0)
	{
		var url = ActionCommons.getElement("slider_fr_url");
		Controller.executeAction('searchpricefr', 'search_listing_fr',url.value);
	}
}

function submitAction(event)
{
	var e = dojo.event.browser.fixEvent(event);
	if (e.keyCode == e.KEY_ENTER) {

		var args = new Array();
		for(var i = 1; i < arguments.length; i++)
		{
			args.push(arguments[i]);
		}
		
		executeAction.apply(null, args);
		return false;
	}
	return true;
}

function submitProductClicked(){
   window.onbeforeunload = null;
   	var anc = $('btnSaveTop');
   	if(anc){
   		anc.innerHTML = 'Saving...';
   		anc.onclick = null;
   	}
   	anc = $('btnSaveBottom');
   	if(anc){
   		anc.innerHTML = 'Saving...';
   		anc.onclick = null;
   	}
}

function disableButton (link, text){
   	var anc = $(link);
   	if(anc){
   		anc.innerHTML = text;
   		anc.onclick = null;
   	}
}

function setFocusOnLoginForm(){
	var element;
	element = $('userlogin_email');
	if(element){
		element.focus();
		element = $('floating_form_body');
		if(element != null) {
			window.scrollTo(0, findTop(element));	
		}		
		return;
	}
	element = $('productsearch_txtbx');
	if(element){
		element.focus();
		return;
	}
	
}

function isReviewRated(){
	//ONLY for addreview action
	var tempRating = $('hdn_rating_review');
	if(tempRating){
		if(tempRating.value == ""  || parseInt(tempRating.value) <= 0){
			//Controller.showMessage("Enter Review Rating", errorTag);
			return false;
		}
	}
	return true;
}

function validateReviewText(value){
	if(dojo.validate.isText(value)){
		//there is some text, should be between 1 to 8000 characters
		var f = { maxlength:8000};
		var ret = dojo.validate.isText(value, f);
		return ret;
	}
	return true;
}

function validateAboutMeText(value){
	if(dojo.validate.isText(value)){
		//there is some text, should be between 1 to 255 characters
		var f = { maxlength:255};
		var ret = dojo.validate.isText(value, f);
		return ret;
	}
	return true;
}

function validateCollectionText(value){
	var collectionText=dojo.string.trim(value);
	if(collectionText.length <=0)
	{
		return false;
	}
	if(dojo.validate.isText(collectionText)){
		//there is some text, should be between 1 to 1000 characters
		var f = { maxlength:1000};
		var ret = dojo.validate.isText(collectionText, f);
		return ret;
	}
	return true;
}
function validateAddProductToCollection(){
	var value = dwr.util.getValue('review_text');
	if(dojo.validate.isText(value)){
		var ret = isReviewRated();
		return ret;
	}
	return true;
}

function checkProductPrice(value){
	//returned true by sarvjeet on May 30, 2010 to override pricing check
	//commented by prashant to reactivate  price validation on 15/12/2011
	//again uncommented by prashant on 16/12/2011 to make it similar like toolbar
	//return true;
	if(value.chartAt(0) == '.' ){
		value = '0'+value;
	}
	if(value == ''){
		return true;
	}
	else if(dojo.validate.isRealNumber(value)){
		if(parseFloat(value) >= 0){
			return true;
		}
	}
	return false;
}

function checkProductComment(value){
	if(value == ''){
		return true;
	}else if(dojo.validate.isText(value)){
		//there is some text, should be between 1 to 500 characters
		var f = { maxlength:1000};
		var ret = dojo.validate.isText(value, f);
		return ret;
	}
}



function validateInterestsText(value){
	if(dojo.validate.isText(value)){
		//there is some text, should be between 1 to 500 characters
		var f = { maxlength:500};
		var ret = dojo.validate.isText(value, f);
		return ret;
	}
	return true;
}

function validateShoppingFavoritesText(value){
	if(dojo.validate.isText(value)){
		//there is some text, should be between 1 to 500 characters
		var f = { maxlength:500};
		var ret = dojo.validate.isText(value, f);
		return ret;
	}
	return true;
}

function checkValidUrl(value)
{
	
	if(value){
		var f = {scheme:'true'}
		if(!dojo.validate.isUrl(value, f)){
			//alert( "Please enter a valid URL");
			return false;
		}
	}
	return true;

}

function validateUrlAndFavoritesStoresText(value)
{
	
	if(value.length>0){
		var f = {scheme:'true'}
		if(!dojo.validate.isUrl(value, f)){
			//alert( "Please enter a valid URL");
			return false;
		}
	}
	if(dojo.validate.isText(value)){
		//there is some text, should be between 1 to 200 characters
		var f = { maxlength:200};
		var ret = dojo.validate.isText(value, f);
		return ret;
	}
	return true;

}

function toggleCollectionFieldsDisplay(id, textareaId){
	var div = $(id);
	var reviewarea = $(textareaId);
	if(div){
		if(div.style.display == 'block'){
			div.style.display = 'none';
			if(reviewarea){
				reviewarea.setAttribute('rows', '15');
			}
		}else {
			div.style.display = 'block';
			if(reviewarea){
				reviewarea.setAttribute('rows', '5');
			}
		}
	}
}

function delayOverlayClose(msg){
	var val = "<span id='floating_form_err_txt'>" + msg + "</span>";
	ActionCommons.getElement("floating_form_large_body").innerHTML = val;
	var v = setTimeout("closeOverlay()", 2 * 1000); //close after 2 seconds
}

function closeOverlay(){
	Controller.executeAction("closeFloatingForm");
}

function validateDiscussionText(value){
	var msg = "Hey there. You\'ll need both a title and a message or a question to start a new discussion.";
	if(!dojo.validate.isText(value) || value =='Type your question or message here...')
	{
		return msg;
	}
	//there is some text, should be between 1 to 6000 characters
	var f = { maxlength:6000};
	var ret = dojo.validate.isText(value, f);
	if(!ret){
		return "Please limit your message or question to 6000 characters.";
	}else {
		return "";
	}
}

function validateDiscussionCommentText(value){
	var msg = "Hey there. You\'ll need to enter some text in your comment.";
	if(!dojo.validate.isText(value) || value =='Type your comment here...')
	{
		return msg;
	}
	//there is some text, should be between 1 to 6000 characters
	var f = { maxlength:5000};
	var ret = dojo.validate.isText(value, f);
	if(!ret){
		return "Please limit your comment to 5000 characters.";
	}else {
		return "";
	}
}

function validateDiscussionTitle(value){
	var msg = "Hey there. You\'ll need both a title and a message or a question to start a new discussion.";
	if(!dojo.validate.isText(value)  || value =='Type your post title here...')
	{
		return msg;
	}
	return "";
}

function validateCollectionCommentText(value){
	var msg = "Hey there. You\'ll need to enter some text in your comment.";
	if(!dojo.validate.isText(value) || value =='Type your comment here...')
	{
		return msg;
	}
	//there is some text, should be between 1 to 6000 characters
	var f = { maxlength:5000};
	var ret = dojo.validate.isText(value, f);
	if(!ret){
		return "Please limit your comment to 5000 characters.";
	}else {
		return "";
	}
}

function validateProductCommentText(value){
	var msg = "Hey there. You\'ll need to enter some text in your comment.";
	if(!dojo.validate.isText(value) || value =='Type your comment here...')
	{
		return msg;
	}
	//there is some text, should be between 1 to 6000 characters
	var f = { maxlength:5000};
	var ret = dojo.validate.isText(value, f);
	if(!ret){
		return "Please limit your comment to 5000 characters.";
	}else {
		return "";
	}
}

function findPos(obj) {
	var curleft = curtop = 0;
	if(obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;	
		} while (obj = obj.offsetParent);
	}
	return [curleft,curtop];
			
}

function findTop (obj) {
	var pos = findPos(obj);
	return pos[1];
}

function showMore (divId, containerDiv, className) {
	if($('dv_' + containerDiv + '_' + divId).className == 'todaybuybop_list_itemtext ' + className) {
		$('dv_'  + containerDiv + '_' + divId).className = 'fulltext';
		$('link_'  + containerDiv + '_' + divId).innerHTML = 'Less...';
	}else {
		$('dv_'  + containerDiv + '_' + divId).className = 'todaybuybop_list_itemtext ' + className;
		$('link_'  + containerDiv + '_' + divId).innerHTML = 'More...';
	}
	
}

function setupMoreLinks (containerDiv) {
	var elements = $$('.todaybuybop_list_itemtext');
	for(var i=0; i<elements.length; i++) {
		var element = elements[i];
		var id = element.id;
		var temp = id.split('_');
		var num = temp[temp.length-1];
		var currentHeight = element.offsetHeight;
		var currentClassName = $(id).className;
		$(id).className = 'fulltext';
		var newHeight =  element.offsetHeight;
		$(id).className = currentClassName;
		if(currentHeight >  newHeight) {
			$('dvlink_' + containerDiv + '_' + num).setStyle({display:'none'});
		}
	}
	
}

function resetActivityLinks () {
	ActionCommons.hideDiv("collection_activities_all");
	ActionCommons.hideDiv("collection_activities_comment");
	ActionCommons.hideDiv("collection_activities_save");
	ActionCommons.hideDiv("collection_activities_review");
	ActionCommons.hideDiv("collection_activities_photo");
	ActionCommons.hideDiv("collection_activities_collection");
	var entityId=$("activityEntityId").value;
	var filterType=$("filterType").value;
	var userId=$("userId").value;
	var urlType=$("urlType").value;
	if($('anchor_all'))
	{
		$('anchor_all').className = '';
		if($('anchor_all').onclick == null)
		{
			var url = "filteredactivities.action?subcontent=1&callingpage=1&userId="+userId+"&activityEntityId="+entityId+"&filterType="+filterType;
			//$('photos_link').onclick = function(event) {executeAction("homepageActivityFilter","pagedproductactivities", url , true, "photos")};
			$('anchor_all').onclick = function(event) {executeAction("collectionActivities","collection_activities_all", url , true, "all")};
		}
	}	
	if($('anchor_comments'))
	{
		$('anchor_comments').className = '';
		if($('anchor_comments').onclick==null)
		{
			if(urlType=='collection')
			{
				filterType=2;
			}
			else if(urlType=='product')
			{
				filterType=5;
			}
			else if(urlType=='communityphoto')
			{
				filterType=10;
			}
			else if(urlType=='collectionphoto')
			{
				filterType=14;
			}
			var url = "filteredactivities.action?subcontent=1&callingpage=1&activityEntityId="+entityId+"&filterType="+filterType;
			//$('photos_link').onclick = function(event) {executeAction("homepageActivityFilter","pagedproductactivities", url , true, "photos")};
			$('anchor_comments').onclick = function(event) {executeAction("collectionActivities","collection_activities_comment", url , true, "comments")};
		}
	}
	if($('anchor_saves'))
	{
		$('anchor_saves').className = '';
		
		if($('anchor_saves').onclick==null)
		{
			filterType=3;
			var url = "filteredactivities.action?subcontent=1&callingpage=1&activityEntityId="+entityId+"&filterType="+filterType;
			//$('photos_link').onclick = function(event) {executeAction("homepageActivityFilter","pagedproductactivities", url , true, "photos")};
			$('anchor_saves').onclick = function(event) {executeAction("collectionActivities","collection_activities_save", url , true, "saves")};
		}
	}	
	if($('anchor_reviews'))
	{
		$('anchor_reviews').className= ''; 
		if($('anchor_reviews').onclick==null)
		{
			if(urlType=='product')
			{
				filterType=6;
			}
			else if(urlType=='profile')
			{
				filterType=17;
			}
			var url = "filteredactivities.action?subcontent=1&callingpage=1&activityEntityId="+entityId+"&filterType="+filterType+"&userId="+userId;
			//$('photos_link').onclick = function(event) {executeAction("homepageActivityFilter","pagedproductactivities", url , true, "photos")};
			$('anchor_reviews').onclick = function(event) {executeAction("collectionActivities","collection_activities_review", url , true, "reviews")};
		}
	}	
	if($('anchor_collections'))
	{
		
		$('anchor_collections').className= '';
		if($('anchor_collections').onclick==null)
		{
			if(urlType=='profile')
			{
				filterType=18;
			}
			else if(urlType=='product')
			{
				filterType=8;
			}
			var url = "filteredactivities.action?subcontent=1&callingpage=1&activityEntityId="+entityId+"&filterType="+filterType+"&userId="+userId;
			//$('photos_link').onclick = function(event) {executeAction("homepageActivityFilter","pagedproductactivities", url , true, "photos")};
			$('anchor_collections').onclick = function(event) {executeAction("collectionActivities","collection_activities_collection", url , true, "collections")};
		
		}
	}	
	if($('anchor_photos'))
	{
		$('anchor_photos').className= '';
		if($('anchor_photos').onclick==null)
		{
			if(urlType=='collection')
			{
				filterType=13;
			}
			else if(urlType=='profile')
			{
				filterType=16;
			}
			else if(urlType=='product')
			{
				filterType=7;
			}
			var url = "filteredactivities.action?subcontent=1&callingpage=1&userId="+userId+"&activityEntityId="+entityId+"&filterType="+filterType+"&userId="+userId;
			//$('photos_link').onclick = function(event) {executeAction("homepageActivityFilter","pagedproductactivities", url , true, "photos")};
			$('anchor_photos').onclick = function(event) {executeAction("collectionActivities","collection_activities_photo", url , true, "photos")};
		}
	}

}

function resetHomePageFilterLinks () {
	ActionCommons.hideDiv("pagedproductactivities_friend");
	//ActionCommons.hideDiv("pagedproductactivities_alert");
	ActionCommons.hideDiv("pagedproductactivities_collection");
	ActionCommons.hideDiv("pagedproductactivities_product");
	//ActionCommons.hideDiv("pagedproductactivities_photo");
	ActionCommons.hideDiv("pagedproductactivities_all");
	ActionCommons.hideDiv("pagedtopmembers_all");
	if($('friends_activity_link')){
		$('friends_activity_link').className = 'loggedin_tabs_gap';
		if($('friends_activity_link').onclick == null) {
			var userId = "";
			if($('hdnUserId')) {
				userId = $('hdnUserId').value;
			}
			var url = "recentfriendactivities.action?callingpage=1&subcontent=1&hidetitle=1&userId=" + userId+"&tabId="+1;
			//$('friends_activity_link').onclick = function(event) {executeAction("homepageActivityFilter","pagedproductactivities", url , true, "friends")};
			$('friends_activity_link').onclick = function(event) {executeAction("homepageActivityFilter","pagedproductactivities_friend", url , true, "friends")};
		}
	}
	/*if($('alerts_link')){
		$('alerts_link').className = 'alerts_container';
		if($('alerts_link').onclick == null) {
			var userId = "";
			if($('hdnUserId')) {
				userId = $('hdnUserId').value;
			}
			//
			//var url = "recentpendinginvites.action?callingpage=1&subcontent=1&hidetitle=1&userId=" + userId;
			var url = "activitiesonuserentities.action?callingpage=1&subcontent=1&hidetitle=1&userId=" + userId+"&tabId="+2;
			//$('alerts_link').onclick = function(event) {executeAction("homepageActivityFilter","pagedproductactivities", url , true, "alerts")};
			$('alerts_link').onclick = function(event) {executeAction("homepageActivityFilter","pagedproductactivities_alert", url , true, "alerts")};
		}
	}*/
	if($('collections_link')){
		$('collections_link').className = 'loggedin_tabs_gap';
		if($('collections_link').onclick == null) {
			var url = "adminusercollections.action?userId=" + $('curatorUserId').value;
			//added by ashish start here 10 june 2010
			//$('collections_link').onclick = function(event) {executeAction("homepageActivityFilter","pagedproductactivities", url , true, "collections")};
			$('collections_link').onclick = function(event) {executeAction("homepageActivityFilter","pagedproductactivities_collection", url , true, "collections")};
		}
	}
	if($('products_link')){
		$('products_link').className = 'loggedin_tabs_gap';
		if($('products_link').onclick == null) {
			//ActionCommons.showDiv("product_categories_homepage");
			var url = "productforhomepage.action";
			//$('products_link').onclick = function(event) {executeAction("homepageActivityFilter","pagedproductactivities", url , true, "products")};
			$('products_link').onclick = function(event) {executeAction("homepageActivityFilter","pagedproductactivities_product", url , true, "products")};
		}
	}	
	if($('all_activity_link')){
		$('all_activity_link').className = 'loggedin_tabs_gap';
		if($('all_activity_link').onclick == null) {
			var url = "allactivities.action?callingpage=1&subcontent=1&hidetitle=1&tabId="+6;
			//$('all_activity_link').onclick = function(event) {executeAction("homepageActivityFilter","pagedproductactivities", url , true, "all")};
			$('all_activity_link').onclick = function(event) {executeAction("homepageActivityFilter","pagedproductactivities_all", url , true, "all")};
		}
	}
	if($('top_member_link')){
		$('top_member_link').className = 'loggedin_tabs_gap';
		if($('top_member_link').onclick == null) {
			var url = "topmembers.action";
			//$('all_activity_link').onclick = function(event) {executeAction("homepageActivityFilter","pagedproductactivities", url , true, "all")};
			$('top_member_link').onclick = function(event) {executeAction("homepageActivityFilter","pagedtopmembers_all", url , true, "topmembers")};
		}
	}
	/*if($('photos_link')){
		$('photos_link').className = 'photoslink_container';
		if($('photos_link').onclick == null) {
			var url = "filteredactivitiesforhomepage.action?filterType=11&callingpage=1&subcontent=1&hidetitle=1&tabId="+5;
			//$('photos_link').onclick = function(event) {executeAction("homepageActivityFilter","pagedproductactivities", url , true, "photos")};
			$('photos_link').onclick = function(event) {executeAction("homepageActivityFilter","pagedproductactivities_photo", url , true, "photos")};
		}
	}*/
}

function resetAddCommentLinks () {
	ActionCommons.hideDiv("collection_productarea_container");
	ActionCommons.hideDiv("addphoto_container");
	ActionCommons.hideDiv("collection_textarea_container");
	ActionCommons.hideDiv("collection_reviewarea_container");
	if($('addcomment_link'))
		{
			$('addcomment_link').className = '';
			if($('addcomment_link').onclick == null)
			{
				$('addcomment_link').onclick =  function(e) { setAddCommentCurrentLink('addcomment_link')};
			}
		}	
	if($('addreview_link'))
		{
			$('addreview_link').className = '';
			if($('addreview_link').onclick == null)
			{
				$('addreview_link').onclick = function(e) { setAddCommentCurrentLink('addreview_link')};
			}
		}
	if($('addphoto_link'))
	{
		$('addphoto_link').className = '';
		if($('addphoto_link').onclick == null)
		{
			$('addphoto_link').onclick = function(e) { setAddCommentCurrentLink('addphoto_link')};
		}
		
	}
	if($('addproduct_link'))
	{
		$('addproduct_link').className = '';	
		if($('addproduct_link').onclick == null)
		{
			$('addproduct_link').onclick = function(e) {setAddCommentCurrentLink('addproduct_link')};
		}
	}
}

function setAddCommentCurrentLink (link) {
	resetAddCommentLinks();
	var span = $('floating_form_err_txt');
	$('imagepost_failure').style.visibility = 'hidden';
	$('imagepost_success').style.visibility = 'hidden';
	$('btnAdd').innerHTML = 'POST';
	if(span){
		span.style.visibility = 'hidden';
	}
	if(link=='addproduct_link')
	{
		ActionCommons.showDiv("collection_productarea_container");
		collectionId = $('hdn_collectionid').value;
		if(collectionId >0)
			{
				$('btnAdd').onclick = function (e) {executeAction('validateCollectionProductPhoto')};
			}
		$('addproduct_link').onclick=null;	
	}
	else if(link=='addreview_link')
	{
		ActionCommons.showDiv("collection_reviewarea_container");
		//var userId = ActionCommons.getElement("userId").value;
		var productId = ActionCommons.getElement("productId").value;
		//var reviewdiv = ActionCommons.getElement("reviewdiv").value;
		//var url = "usercollectionsforreview.action?userId="+userId+"&productId="+productId+"&reviewdiv="+reviewdiv;
		//alert(url);
		if(productId > 0)
		{
			$('btnAdd').onclick = function (e) {executeAction('addReview')};
		}
		$('addreview_link').onclick=null;
	}
	else if(link=='addphoto_link')
	{
		//added by ashish for getting collection id
		collectionId = $('hdn_collectionid').value;
		ActionCommons.showDiv("addphoto_container");
		if($('btnAdd')) {
			//added by ashish for Collection photo on april 19 2010
			if(collectionId >0)
			{
				$('btnAdd').onclick = function (e) {executeAction('validateCollectionPhoto')};
			}
			else
			{
				$('btnAdd').onclick = function (e) {executeAction('validateCommunityPhoto')};
			}
		}
		$('addphoto_link').onclick=null;
	}
	else
	{
		ActionCommons.showDiv("collection_textarea_container");
		if($('btnAdd')) {
			if($('hdnProductId')) {
				$('btnAdd').onclick = function (e) {executeAction('validateProductComment')};
			}else if($('hdnCommunityPhotoId')){
				$('btnAdd').onclick = function (e) {executeAction('validateCommunityPhotoComment')};
			}else if($('hdnCollectionPhotoId')){
				$('btnAdd').onclick = function (e) {executeAction('validateCollectionPhotoComment')};
			}else {
				$('btnAdd').onclick = function (e) {executeAction('validateCollectionComment')};
			}
		}
		$('addcomment_link').onclick=null;
	}
	
	if($(link))
		$(link).className = 'current';
}

function validateCommunityPhotoCommentText(valueComment,valueImage){
	var msgImage   = "Are you forgetting to select an image?"
	var commentText=dojo.string.trim(valueComment);
	var imagePath=dojo.string.trim(valueImage);
	if(commentText=='Type your comment here... it\'s optional.' || commentText=='')
	{	
	}
	else if(commentText.length > 1 && commentText.length >5000 ){
		return "Please limit your comment to 5000 characters.";
	}
	if(imagePath=='')
	{
		return msgImage;
	}
	return "";
}

/* comment on community photo is validated */

function validatePhotoCommentText(value){
	var msg = "Hey there. You\'ll need to enter some text in your comment.";
	if(!dojo.validate.isText(value) || value =='Type your comment here...')
	{
		return msg;
	}
	//there is some text, should be between 1 to 6000 characters
	var f = { maxlength:5000};
	var ret = dojo.validate.isText(value, f);
	if(!ret){
		return "Please limit your comment to 5000 characters.";
	}else {
		return "";
	}
}

function setHomePageActivityLinks (filterType) {
		var reload = false;
		/*var tabValue=$("activeTabValue").value;
		var friendReload=true;
		var collectionReload=true;
		if(tabValue == 1)
		{
			friendReload=false;
		}
		else if(tabValue == 3)
		{
			collectionReload=false;
		}
		*/
		Controller.executeAction("closeFloatingForm");
		if(filterType) {
			
			//var info_text = 'most recent activity shown first';
			resetHomePageFilterLinks();
			if(filterType == 'all') {
				if($('all_activity_link')){
					ActionCommons.showDiv("pagedproductactivities_all");
					ActionCommons.hideDiv("product_categories_homepage");
					$('all_activity_link').className = 'loggedin_tabs_current';
					//$('activity_tagline').className='righttext';
					$('all_activity_link').onclick = null;
				}
				if(window.pagedproductactivities_all == false || !(window.pagedproductactivities_all)){
					window.pagedproductactivities_all = true;
					reload = true;
				}			
			}else if (filterType == 'products') {
				if($('products_link')){
					ActionCommons.showDiv("pagedproductactivities_product");
					ActionCommons.showDiv("product_categories_homepage");
					$('products_link').className = 'loggedin_tabs_current';
					//$('activity_tagline').className='righttext';
					$('products_link').onclick = null;
					//info_text = 'recently added products';
				}
				if(true)
				{
					if(window.pagedproductactivities_product == false || !(window.pagedproductactivities_product)){
						window.pagedproductactivities_product = true;
						reload = true;
					}
				}
			}else if (filterType == 'friends') {
				if($('friends_activity_link')){
					ActionCommons.showDiv("pagedproductactivities_friend");
					ActionCommons.hideDiv("product_categories_homepage");
					$('friends_activity_link').className= 'loggedin_tabs_current';
					//$('activity_tagline').className='righttext';
					$('friends_activity_link').onclick = null;
				}
				if(window.pagedproductactivities_friend == false || !(window.pagedproductactivities_friend)){
						window.pagedproductactivities_friend = true;
						reload = true;
					}
				
			}else if (filterType == 'topmembers') {
				if($('top_member_link')){
					ActionCommons.showDiv("pagedtopmembers_all");
					ActionCommons.hideDiv("product_categories_homepage");
					$('top_member_link').className= 'loggedin_tabs_current';
					//$('activity_tagline').className='righttext';
					$('top_member_link').onclick = null;
				}
				if(window.pagedtopmembers_all == false || !(window.pagedtopmembers_all)){
						window.pagedtopmembers_all = true;
						reload = true;
					}
				
			}
			else if (filterType == 'collections') {
				if($('collections_link')){
					ActionCommons.showDiv("pagedproductactivities_collection");
					ActionCommons.hideDiv("product_categories_homepage");
					$('collections_link').className = 'loggedin_tabs_current';
					//$('collections_link').className = 'collectionlink_container_current';
					//$('activity_tagline').className='leftext';
					$('collections_link').onclick = null;
					info_text = 'featured member collections:';
				}
				//if(collectionReload)
				//{
				if(window.pagedproductactivities_collection == false || !(window.pagedproductactivities_collection)){
					window.pagedproductactivities_collection = true;
					reload = true;
				}
				//}
			}/*else if (filterType == 'alerts') {
				if($('alerts_link')){
					ActionCommons.showDiv("pagedproductactivities_alert");
					$('alerts_link').className = 'alerts_container_current';
					$('activity_tagline').className='righttext';
					$('alerts_link').onclick = null;
				}
				if(window.pagedproductactivities_alert == false || !(window.pagedproductactivities_alert)){
					window.pagedproductactivities_alert = true;
					reload = true;
				}
			}else if (filterType == 'photos') {
				if($('photos_link')){
					ActionCommons.showDiv("pagedproductactivities_photo");
					$('photos_link').className= 'photoslink_container_current';
					$('activity_tagline').className='righttext';
					$('photos_link').onclick = null;
					info_text = 'recently added photos';
				}
				if(window.pagedproductactivities_photo == false || !(window.pagedproductactivities_photo)){
					window.pagedproductactivities_photo = true;
					reload = true;
				}
			}
			if($('info_text')) {
				$('info_text').innerHTML = info_text;
			}*/
		}
		return reload;
}

dojo.event.topic.subscribe("/homepageactivities", function(data, type, request) {
  //cancel request
  //request.cancel= true;
  //alert(type + ":" + window.homepagerequestactive);
  if(type == 'before') {
  	window.homepagerequestactive = true;
  }else if (type == 'load' || type == 'error') {
  	window.homepagerequestactive = false;
  }
  //alert(type + ":" + window.homepagerequestactive);
});

function facebookConnect() {
	FB.login(function(response) {
  		executeAction("facebookLogin", response);
	}, {scope:'email,publish_stream,offline_access, read_friendlists, status_update'});

}

function checkLoginStatus() {
	FB.login(function(response) {
  		executeAction("facebookLogin", response);
	});
}

function parseFBML(divId) {
	if(FB && FB.XFBML){
		try {
			FB.XFBML.parse($(divId));
		}catch (error) {
		}
	}
}

//added by ashish on 13 may 2010

function resetActivityCategoryLinks () {
	ActionCommons.hideDiv("pagedcategoryactivities_all");
	ActionCommons.hideDiv("pagedcategoryactivities_collections");
	ActionCommons.hideDiv("pagedcategoryactivities_products");
	ActionCommons.hideDiv("pagedcategoryactivities_photos");
	ActionCommons.hideDiv("pagedcategoryactivities_discussions");
	var catId=$('categoryId').value;
	if($('anchor_all')){
		$('anchor_all').className = '';
			if($('anchor_all').onclick == null) {
			var url = "pagedproductactivitiesbycategory.action?subcontent=1&callingpage=1&hidetitle=1&containerDiv="+"pagedcategoryactivities_all"+"&categoryId="+catId;
			//$('photos_link').onclick = function(event) {executeAction("homepageActivityFilter","pagedproductactivities", url , true, "photos")};
			$('anchor_all').onclick = function(event) {executeAction("homepageCategoryFilter","pagedcategoryactivities_all", url , true, "all")};
			}
		}
	if($('anchor_collections')){
		$('anchor_collections').className= '';
		if($('anchor_collections').onclick == null) {
			var url = "categorycollections.action?hideAllProducts=1&categoryId="+catId;
			//$('photos_link').onclick = function(event) {executeAction("homepageActivityFilter","pagedproductactivities", url , true, "photos")};
			$('anchor_collections').onclick = function(event) {executeAction("homepageCategoryFilter","pagedcategoryactivities_collections", url , true, "collections")};
		}	
		}
	if($('anchor_discussions')){
		$('anchor_discussions').className= '';
			if($('anchor_discussions').onclick == null) {
			var url = "pagedcategorydiscussions.action?callingpage=1&categoryId="+catId;
			//$('photos_link').onclick = function(event) {executeAction("homepageActivityFilter","pagedproductactivities", url , true, "photos")};
			$('anchor_discussions').onclick = function(event) {executeAction("homepageCategoryFilter","pagedcategoryactivities_discussions", url , true, "discussions")};
			}
		}
	if($('anchor_reviews')){
		$('anchor_reviews').className= '';
			if($('anchor_reviews').onclick == null) {
			var url = "subcategoryhome.action?tab=1&categoryId="+catId;
			//$('photos_link').onclick = function(event) {executeAction("homepageActivityFilter","pagedproductactivities", url , true, "photos")};
			$('anchor_reviews').onclick = function(event) {executeAction("homepageCategoryFilter","pagedcategoryactivities_products", url , true, "products")};
			}
		}
	if($('anchor_photos')){
		$('anchor_photos').className= '';
			if($('anchor_photos').onclick == null) {
			var url = "filteredcategoryproductphotos.action?callingpage=1&subcontent=1&hidetitle=1categoryId="+catId+"&containerDiv="+"pagedcategoryactivities_photos";
			//$('photos_link').onclick = function(event) {executeAction("homepageActivityFilter","pagedproductactivities", url , true, "photos")};
			$('anchor_photos').onclick = function(event) {executeAction("homepageCategoryFilter","pagedcategoryactivities_photos", url , true, "photos")};
			}
			
		}

				
}

/* added by ashish on 31 may 2010 */

function validateCollectionProductPhotoUrl(value){
	var collectionProductUrl=dojo.string.trim(value);
	if(collectionProductUrl=="enter a product URL to add a product from another site ...")
	{
		return "Please enter valid product Url.";
	}
	else if(collectionProductUrl.length <=0)
	{
		 return "Please enter valid product Url.";;
	}
	else
	{
		return "true";
	}	
	
}

function validateProductImageUrl(value){
	var productImageUrl=dojo.string.trim(value);
	if(productImageUrl == "paste an image URL")
	{
		return "Please enter an image URL.";
	}
	else if(productImageUrl.length <=0)
	{
		 return "Please enter an image URL.";
	}
	else
	{
		return "true";
	}	
	
}

function showImage(url, container) {
	if(url.length > 0) {
		var div = $(container);
		if(div) {
			var img = $(container + "_img");
			img.src = "/resources/upload/" +  url.replace(/\134/g,"/");
			img.alt = "product image";
			if(div.style.display != 'block')
				div.style.display = 'block';
			
		}
	}
	
}

function showUploadedImages() {
	//by sarvjeet on May 31, 2010 for showing uploaded image
	var element;
	element = $('addproduct_photo_hidden');
	if(element != null && element.value.length > 0) {
		showImage(element.value, 'uploadedImageHolder');
	}
	element = $('addproduct_photobyurl_hidden');
	if(element != null && element.value.length > 0) {
		showImage(element.value, 'uploadedImageByUrlHolder');
	}
	if($('imageType').value == 'uploaded'){
		setSelectedImage($('uploadedImageHolder'));
	}
	if($('imageType').value == 'uploadedbyurl'){
		setSelectedImage($('uploadedImageByUrlHolder'));
	}
}

function setSelectedImage(div) {
	if(div != null) {
		removeBorder();
		div.style.border = '0.39em solid #1D96CE';	
		if(div.id == 'uploadedImageHolder') {
			$('imageType').value = 'uploaded';
		}else if (div.id == 'uploadedImageByUrlHolder') {
			$('imageType').value = 'uploadedbyurl';
		}
	}
}

function removeBorder() {
	if(selectedDiv != null){
		selectedDiv.style.borderColor = selectedDiv.style.borderWidth = selectedDiv.style.borderStyle = '';
	}
	selectedDiv = null;
	var div = $('uploadedImageHolder');
	if(div) {
		div.style.borderColor = div.style.borderWidth = div.style.borderStyle = '';
	}
	div = $('uploadedImageByUrlHolder');
	if(div) {
		div.style.borderColor = div.style.borderWidth = div.style.borderStyle = '';
	}
}

/* added by ashish on 09 june 2010 */
function isReviewText(){
	//ONLY for addreview action
	var tempReview = $('review_text');
	if(tempReview){
		if(tempReview.value == ""  || tempReview.value == "what's your experience with this product?" ){
			//Controller.showMessage("Enter Review Rating", errorTag);
			return false;
		}
	}
	return true;
}

function checkProductTitle(){
	var productText = $('addproduct_title');
	if(productText.value == ""  || productText.value == "enter product title")
	{
		return false;
	}
	return true;
}

function validateEmailArray (txt) {
	if(!dojo.validate.isText(txt))return false;
	var arEmails = txt.split(',');
	if(arEmails.length == 1){
		//let us try with ; as well
		arEmails = txt.split(';');
	}
	if(arEmails.length > 0) {
		for(var i=0;i<arEmails.length;i++){
			if(!dojo.validate.isEmailAddress(dojo.string.trim(arEmails[i]))){
				return false;
			}
		}
	}else {
		return false;
	}
	return true;
}

function delayOverlayPassword(msg){
	ActionCommons.getElement("floating_form_body").innerHTML = msg;
	var v = setTimeout("closeOverlay()", 2 * 1000); //close after 2 seconds
}

function validateRegisterEmail(inputvalue){
	//var pattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
	// updated by Prashant on 28 - 12 - 2011
	var emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
	if(inputvalue.match(emailRegex)){
		return true;
	}else{
		return false;
	}
	
   /* if(dojo.validate.isEmailAddress(inputvalue)){         
		return true;   
    }else{   
		return false; 
    }*/
}

function validateDisplayName(text)
{
	var f = {minlength:1, maxlength:50};
	return dojo.validate.isText(text, f);
}

function validatePassword(text)
{
	var f = {minlength:1, maxlength:50};
	return dojo.validate.isText(text, f);
}

function validateReviewCommentText(text)
{
	var f = {minlength:1, maxlength:250};
	return dojo.validate.isText(text, f);
}

function enableButton(button, buttonText, actionName, isError) {
		if(isError) $('floating_form_err_txt').style.visibility='visible';
		$(button).innerHTML = buttonText;
		$(button).onclick = function(event){executeAction(actionName)};
}

// added by ashish on 20 oct 2010

function openFacebookLogin(obj){
	if($('chkFacebook').checked){
		FB.login(function(response) {
			if (response.authResponse) {
			      // A user has logged in, and a new cookie has been saved
			      var uid = response.authResponse.userID;
			      var access_token = response.authResponse.accessToken;
				if(uid == null || access_token == null) {
				  	if($('showFaceBookMessage') != null) {
					  	ActionCommons.showDiv("showFaceBookMessage")
						$('showFaceBookMessage').innerHTML = "Hey there! You need to login on facebook and grant us permission to post the product on facebook.";
				  	}else {
				  		throw "Facebook login error."  
				  	}
				  	$('chkFacebook').checked = false;
				  	return;
				}  
			  	var url = "/me?fields=id,name,email,picture&access_token=" + access_token;
			  	FB.api("/me",  function(userInfo) {
				var email = userInfo.email;
				var name = userInfo.name;
				executeAction("linkToUpdateFacebookId", uid,email);
				//executeAction("userLoginByFacebook", uid, access_token, email, name);
				})
		  	}else {
			  	//alert('Hey there! You will have to login on facebook and allow us to post your product on facebook.');
			  	if($('showFaceBookMessage') != null) {
				  	ActionCommons.showDiv("showFaceBookMessage")
					$('showFaceBookMessage').innerHTML = "Hey there! You will have to login on facebook and allow us to post your product on facebook.";
			  	}else {
			  		throw "Facebook login error."  
			  	}
			  	$('chkFacebook').checked = false;
		  	}
	  	}, { scope: 'email, publish_stream, offline_access, read_friendlists, status_update' });
	}else {
		if($('showFaceBookMessage') != null) {
			ActionCommons.hideDiv("showFaceBookMessage")
		}
	}
	
}
 
function sendToTwitter(productId,collection_url) {
	if($('postToTwitter').value == 1) {
		 if(BitlyClient){
			 if($('err_text') != null) {
				 $('err_text').innerHTML = "Using bit.ly to shorten the Url....";
			 }
			 var url = "http://wanelo.com/product/"+productId;
			 BitlyClient.shorten(url, 'bitlyResponse');
		 }else {
		 	if($('err_text') != null) {
			 	$('err_text').innerHTML = 'error! bit.ly api was not initialized';
		 	}else {
		 		throw "bit.ly api not initialized.";
		 	}
		 }
	}else {
		if(collection_url != undefined){
			Controller.executeAction("showSubContent",  collection_url, true);
		}else {
			Controller.executeAction("closeFloatingForm");
		}
	}
}


function bitlyResponse (data) {
    var bitly_link = null;
    for (var r in data.results) {
        bitly_link = data.results[r]['shortUrl']; 
        break;
    }
	if(bitly_link == null) {
		if($('err_text') != null) {
			$('err_text').innerHTML = 'Could not shorten the url using bit.ly';
		}else {
			throw ("url shortening error.");		
		}
		return;
	} 
	if($('err_text') != null) {
	    $('err_text').innerHTML = 'bit.ly url:' + bitly_link;
	}   
    var twitterUrl = "http://twitter.com/home?status=I've bookmarked " + $('productTitle').value +  " on @wanelo " + encodeURIComponent(bitly_link);
	var collection_url = null;
	if($("collectionId") != null) {
		var collectionId = $("collectionId").value;
		var userId = $("userId").value;
		collection_url = "listcollectiondetails.action?success=1&amp;id=" + collectionId + "&amp;userId=" + userId + "&mymenu=yes";
	}
    openTwitterWindow(twitterUrl,'err_text','posting_image', collection_url);
}

function openTwitterWindow(url, error_target, container_div, collection_url) {
//  	var redirect = true;
  	if($(error_target) != null) {
	  	$(error_target).innerHTML = "Posting on twitter....";
  	}
  	var w = window.open(url);
  	setTimeout(function(){chromeBlockerCallback(w,url, error_target, container_div, collection_url)}, 2000);
  	Controller.executeAction("closeFloatingForm");
//  	if(!w|| w.closed || typeof w.closed=='undefined') {
  		//popup might be blocked
  		//work for google chrome
//  		setTimeout(function(){chromeBlockerCallback(w,url, error_target, container_div, collection_url)}, 2000);
//  	}else {
//	  	$('err_text').innerHTML = "Done. Please wait while we redirect you....";
//  	}
//  	return redirect;
}

function chromeBlockerCallback(w,url, error_target, container_div, collection_url){
	var redirect = true;
	var innerHeight = null;
	try {
		innerHeight = w.innerHeight;
	}catch (error){}
	if((!w|| w.closed || typeof w.closed=='undefined') || (innerHeight != null && parseInt(innerHeight) == 0)) {
 		redirect = false;
 		if($(error_target) != null) {
	 		$(error_target).innerHTML = "hey! looks like that your browser has blocked the window for twitter.";
 		}else {
 			throw "open window for twiiter failed.";
 		}
 		var container = $(container_div);
 		container.innerHTML = "";
 		var element = document.createElement("a");
 		element.innerHTML = "open twitter window";
 		element.href = url;
 		element.target = "_blank";
 		container.appendChild(element);
 		element = document.createElement("span");
 		element.innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
 		container.appendChild(element);
 		element = document.createElement("a");
 		element.href = "javascript:Controller.executeAction('showSubContent',  '" + collection_url + "', true);";
 		element.innerHTML = "back to wanelo";
 		$(container_div).appendChild(element);
	}
 	if(collection_url == null) return;
 	if(redirect)Controller.executeAction("showSubContent",  collection_url, true);
}

function resetLinksOnHomePage() {
	Controller.executeAction("closeFloatingForm");
	var ul = $('catList');
	if(ul) {
		var anchors = ul.getElementsByTagName('a');
		if(anchors) {
			for (var i=0; i<anchors.length; i++) {
				var anchor = anchors[i];
				$(anchor).className = '';
				//$(anchor).onclick = '';
			}
		}
	}
	if($('all_products') != null){
		$('all_products').className = '';
	}
		
	
}

function resetFiltersDiv() {
	var dv = $('dv_filters');
	if(dv) {
		var anchors = dv.getElementsByTagName('a');
		if(anchors) {
			for (var i=0; i<anchors.length; i++) {
				var anchor = anchors[i];
				$(anchor).className = '';
				//$(anchor).onclick = '';
			}
		}
	}
}

function resetProductTypesDiv() {
	var dv = $('dv_producttypes');
	if(dv) {
		var anchors = dv.getElementsByTagName('a');
		if(anchors) {
			for (var i=0; i<anchors.length; i++) {
				var anchor = anchors[i];
				$(anchor).className = '';
				//$(anchor).onclick = '';
			}
		}
	}
}

/* added by ashish to check uniqueness for userName */
function checkUserNameEntered(userName){
	if(userName.length < 1)
	{
		throw "Please enter a username.";
	}
	if(userName.length > 50)
	{
		throw "Please limit url to 50 characters.";
	}
		
	/*if(hasWhiteSpace(userName))
	{
		throw "Sorry no space allowed.";
	}*/	
	// we are removing _ and . from special characters
	var iChars = "!@#$%^&*()+=-[]\\\';.,/{}|\":<>?~' '";
	for (var i = 0; i < userName.length; i++) {
	  	if (iChars.indexOf(userName.charAt(i)) != -1) {
	  	  throw "Hey there. Url can only have numbers, alphabets or an underscore.";
	  	}
  	}
  	 return true;
}

 function hasWhiteSpace(s)
 {
    var iChars=" ";
    for (var i = 0; i < s.length; i++) {
  	if (iChars.indexOf(s.charAt(i)) != -1) {
  	  return true;
  	}
  	}
	return false;
 } 

 function fbFriendInvite(faceBookId, userId)
{
	var newDiv = document.createElement('div');
	var fbmlString ="";
	fbmlString = "<fb:serverfbml style=\"width: 700px; height: 400px;\">";
	fbmlString += " <script type=\"text/fbml\">";
	fbmlString += " <fb:fbml>";
	//fbmlString += " <h1><a href=\"#\" onclick=\"new Dialog().showMessage('About wanelo', 'wanelo is a great place to bookmark and share products with your friends.'); return false;\">About wanelo</a></h1><br />";


	fbmlString += " <fb:request-form";
	fbmlString += " action=\"http://wanelo.com/index.action?DoLogin=true&route=fbsendinvite&contentaction=invite&userId=" + userId + "\"";
	fbmlString += " method=\"POST\"";
	fbmlString += " invite=\"true\"";
	fbmlString += " type=\"Wanelo\"";
	//fbmlString += " content=\"Join wanelo to bookmark and share your products. <fb:req-choice url='http://wanelo.com' label='see app' /> \">";
	fbmlString += " content=\"<fb:name uid='" + faceBookId + "' useyou='false' /> is inviting you to Wanelo.com to bookmark and share your favorite products. Click &quot;Accept&quot;  to check it out.<fb:req-choice url='http://wanelo.com/index.action?route=fbreceiveinvite&contentaction=profile&userId=" + userId +  "' label='Accept' />\">";
	fbmlString += " <fb:multi-friend-selector";
	fbmlString += " showborder=\"true\" bypass=\"cancel\"";
	fbmlString += " actiontext=\"Invite your friends to Wanelo to share products.\">";
	fbmlString += " </fb:request-form>";
	fbmlString += " </fb:fbml>  ";
	fbmlString += " <\/script>  ";
	newDiv.innerHTML = fbmlString;
	var container = document.getElementById('invite_div');
	container.innerHTML = "";
	container.style.display = 'block';
	container.appendChild(newDiv);
	FB.XFBML.parse(container);
}

function facebookLoginToInviteFriends(alreadyLinked, userId, faceBookId, findFacebookContacts) {
	FB.login(function(response) {
		if (response.authResponse) {
		      // A user has logged in, and a new cookie has been saved
		      var uid = response.authResponse.userID;
		      var access_token = response.authResponse.accessToken;
			if(uid == null || access_token == null) {
			  	ActionCommons.showDiv("showFaceBookMessage")
				$('showFaceBookMessage').innerHTML = "Hey there! You need to login on facebook and grant us permission to post the product on facebook.";
			  	return;
			}  
		  	var url = "/me?fields=id,name,email,picture&access_token=" + access_token;
		  	FB.api("/me",  function(userInfo) {
			var email = userInfo.email;
			var name = userInfo.name;
			if(!alreadyLinked){
				executeAction("linkToUpdateFacebookId", uid,email);
			}else {
				faceBookId = uid;
			}
			if(findFacebookContacts != undefined){
				//do nothing
			}else {
				fbFriendInvite(faceBookId, userId);
			}
			})
	  	}else {
		  	//alert('Hey there! You will have to login on facebook and allow us to post your product on facebook.');
		  	ActionCommons.showDiv("showFaceBookMessage")
			$('showFaceBookMessage').innerHTML = "Hey there! You will have to login on facebook and allow us to post your product on facebook.";
	  	}
  	}, { scope: 'email, publish_stream, offline_access, read_friendlists, status_update' });

}

function resetBoardingSteps()
{
	$('btn_prev').style.display = 'none';
	$('btn_skip_next').style.display = 'none';
	$('btn_done').style.display = 'none';
	$('onboarding_topmembers').className='members';
	$('onboarding_friends').className='friends';
	$('onboarding_uploadphoto').className='photo';
	$('onboarding_toolbar').className='toolbar';
}

function validateEmailForFacebook(email) {
   var tempEmailName=dojo.string.trim(email);
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   if(reg.test(tempEmailName) == false) {
      //alert('Invalid Email Address');
      return false;
   }
   
   var intIndexOfMatch = tempEmailName.indexOf("@facebook.com");
   while (intIndexOfMatch != -1){
	    //alert('@facebook.com found in email');
        return false;
	}
	return true;
}

function isSessionCheckRequired(){
	//if session has not been checked in last 20 minutes or last check time is zero, then it is required
	if($('stime') == null || $('stime') == undefined){
		return true;
	}
	var sTime = $('stime').value;
	if(sTime == '0'){
		return true;
	}
	var curDate = new Date();
	var cTime = curDate.getTime();
	var diff = cTime - sTime;
	var maxDiff = 20 * 60 * 1000; //20 mins * 60 sec * 1000 msec
	if(diff > maxDiff){
		return true;
	}
	return false;
}

function validateOnsaleForm() {
	var val;
	var errorSpan = $('floating_form_err_txt');
	val = $('onsale_purchaseprice').value;
	if(!(dojo.validate.isRealNumber(val)   && parseFloat(val) > 0)){
		errorSpan.style.visibility = 'visible';
		errorSpan.innerHTML = "Please enter valid purchase price.";
		return false;
	}
	val = $('onsale_mrp').value;
	if(!(dojo.validate.isRealNumber(val)   && parseFloat(val) > 0)){
		errorSpan.style.visibility = 'visible';
		errorSpan.innerHTML = "Please enter valid MRP.";
		return false;
	}
	val = $('onsale_saleprice').value;
	if(!(dojo.validate.isRealNumber(val)   && parseFloat(val) > 0)){
		errorSpan.style.visibility = 'visible';
		errorSpan.innerHTML = "Please enter valid sale price.";
		return false;
	}
	val = $('onsale_paypalid').value;
	if(dojo.validate.isText(val)){
		//there is some text, should be between 1 to 8000 characters
		var f = { maxlength:500};
		var ret = dojo.validate.isText(val, f);
		if(!ret){
			errorSpan.style.visibility = 'visible';
			errorSpan.innerHTML = "Please enter valid paypal button id.";
			return false;
		}
	}else {
		errorSpan.style.visibility = 'visible';
		errorSpan.innerHTML = "Please enter valid paypal button id.";
		return false;
	}
	errorSpan.style.visibility = 'hidden';
	executeAction('onsaleProduct');
	
	//if(dojo.validate.isText(value)){
}

//added by sarvjeet/prasant on Dec 23, 2011
function resetFilters() {
	var dv = $('hometabs');
	if(dv) {
		var anchors = dv.getElementsByTagName('a');
		if(anchors) {
			for (var i=0; i<anchors.length; i++) {
				var anchor = anchors[i];
				$(anchor).className = '';
				//$(anchor).onclick = '';
			}
		}
	}
}

