/**
 * A map that translates between Fina's subcodes and human readable text.
 */
function KidRobotSolrUtils(){
    this.data=null;
    //this.varUtils=new VarUtils();
    this.selectedValues=null;
    this.unselectedValues=null;
    this.translationMap=null;
    
    this.dropDownCollections={
        manufacturer:["category","artists","material"],
        site:["category","artists","material"],
        standard:["category","artists","material"]    
    };
}

KidRobotSolrUtils.prototype.defaultTranslator=function(value,dropDown){
    return value;
}

KidRobotSolrUtils.prototype.translateByMap=function(value,dropDown){
    var translation=null;
    //var translation=value;
    if (varUtils.isDef(dropDown.xlateData) && varUtils.isDef(dropDown.xlateData[value])){
        translation=dropDown.xlateData[value];
    }

    return translation;
}

KidRobotSolrUtils.prototype.init=function(searchResponse, selectedValues, unselectedValues, translationMap){
    this.selectedValues=selectedValues;
    this.unselectedValues=unselectedValues;
    this.translationMap=translationMap;
    
    if (!varUtils.isDef(translationMap.filter_by_category)){
        var filterByCategory=new Object();
        for(var i in translationMap){
            for(var j in translationMap[i]){
                filterByCategory[j]=translationMap[i][j];
            }    
        }
        
        this.translationMap.filter_by_category=filterByCategory;
    }
    
    var json=searchResponse;
    if (varUtils.isDef(searchResponse)){
        if (typeof(searchResponse) == "string"){
            json=searchResponse.evalJSON();
        }
        this.data=new Object();
        this.data.facets=new Object();
        this.data.facets.price=json.facet_counts.facet_queries;
        this.data.facets.fields=json.facet_counts.facet_fields;
        /*if (!varUtils.isDef(this.data['searchFailed']) || !this.data['searchFailed']){ 
            initializeData(data);
        }*/
    }
}

KidRobotSolrUtils.prototype.makeArtistsDropDown=function(values,selected){
    var dropDown=solrFilterUtils.makeDropDown("Artist","Artist","filter_by_brand",2,solrFilterUtils.renderHandlers.renderByValue,values,selected);
    dropDown.selectedValue=this.selectedValues.brand;
    return dropDown;
}

KidRobotSolrUtils.prototype.makePricingDropDown=function(values,selected){
    var dropDown=solrFilterUtils.makeDropDown("Price Range","Any Price","filter_by_price",1,solrFilterUtils.renderHandlers.renderPrice,values,selected);
    dropDown.selectedValue=this.selectedValues.price;
    return dropDown;
}

KidRobotSolrUtils.prototype.makeCategoryDropDown=function(values,selected){
    var dropDown=solrFilterUtils.makeDropDown("Category","Category","filter_by_category",2,solrFilterUtils.renderHandlers.renderByValue,values,selected);
    dropDown.xlateData=this.translationMap["filter_by_category"];
    //dropDown.translator=KidRobotSolrUtils.prototype.translateByMap;
    dropDown.selectedValue=this.selectedValues.category;
    return dropDown;
}

KidRobotSolrUtils.prototype.makeMaterialDropDown=function(values,selected){
    var dropDown=solrFilterUtils.makeDropDown("Material","Material","filter_by_material",2,solrFilterUtils.renderHandlers.renderByValue,values,selected);
    dropDown.selectedValue=this.selectedValues.material;
    return dropDown;
}

KidRobotSolrUtils.prototype.buildDropDowns=function(collection){
    var dropDowns=null;
    if (varUtils.isDef(this.data) && varUtils.isDef(this.data.facets)){
        if (varUtils.isDef(this.data.facets.fields) && varUtils.isDef(collection)){
            var collections=this.dropDownCollections[collection];
            dropDowns=new Array();
            for (var i=0;i<collections.length;++i){
                if (collections[i]=="artists"){
                    dropDowns.push(this.makeArtistsDropDown(this.data.facets.fields.facet_brand));
                } else if (collections[i]=="category"){
                    dropDowns.push(this.makeCategoryDropDown(this.data.facets.fields.facet_category_name));
                } else if (collections[i]=="material"){
                    dropDowns.push(this.makeMaterialDropDown(this.data.facets.fields.facet_material));
                } else if (collections[i]=="pricing"){
                    dropDowns.push(this.makePricingDropDown(this.data.facets.price));
                }
            }
        }
    }
    
    return dropDowns;
}

function KidRobotPaginationUtils(solrResultPaginator){
    this.solrResultPaginator=solrResultPaginator;
}

KidRobotPaginationUtils.prototype.setResultPaginator=function(resultPaginator){
    this.solrResultPaginator=resultPaginator;
}

KidRobotPaginationUtils.prototype.renderPagination=function(paginationContainer,resultCount){
    this.solrResultPaginator.renderPagination(paginationContainer,resultCount);
}

KidRobotPaginationUtils.prototype.renderProducts=function(products,imageSize,linkType){
	var placeholder_url = staticImgPath + "/product_medium-blank.gif";
	
    var rowNum=0;
    if (varUtils.isDef(products)){
        for(var x = 0; x < products.length; x++){
            var link=products[x][linkType].replace(/^null/,contextPath);
            var unformatted=parseInt(products[x].price * 100);
            var price=varUtils.formatCurrency(convert_to_dollars(Math.round(products[x].price * 100)));
            var isNewRow=((x%rowLength)==0);
            var colspan=1;

            if (x==(products.length-1)){
                colspan=rowLength-(x%rowLength);
            }
            
            if (isNewRow){
                rowNum=Math.floor(x/rowLength);
                var row="<tr id='row"+rowNum+"'></tr>";
                jQuery(row).appendTo("#prodlist");
            } 
            
            var img_src = placeholder_url;
            if(varUtils.isDef(products[x].image_url) && products[x].image_url != null){
            	img_src = '/kidrobot_images/products/' + products[x].image_url;
            }
            
            
            jQuery("<td colspan="+colspan+">"
            			+"<a href='/" + link +"'><img width='180' height='187' src='" + img_src + "' /></a>"
            			+"<h3><a href='/"+link+"' title='"+encodeURIComponent(products[x].name).replace(/'/,"\\'")+" By: " + encodeURIComponent(products[x].brand).replace(/'/,"\\'")+"'>"+products[x].name+ "</a></h3>"
                        +"<p>By: " + products[x].brand + "</p>"
                        +"<p class='price'>"+((unformatted+0)>0?"$" + price:"") + "</p></td>").appendTo("#row"+rowNum);
        }
    }
}


function submit_email_subscription(){
	new Ajax.Request( contextPath + '/servlet/EmailSubscriptionServlet', {
		method: 'post',
		parameters: { randid: Math.random() },
		onSuccess: function(transport) {
			if (transport.responseText.indexOf('not valid') >= 0){
				$('sub_confirm').style.display='none';
				$('sub_error').innerHTML ='Please enter a valid email address. For example, name@domain.com.';
				$('sub_error').style.display='';
			}else if (transport.responseText.indexOf('required') >= 0){
				$('sub_confirm').style.display='none';
				$('sub_error').innerHTML = 'Please enter an email address. For example, name@domain.com.';
				$('sub_error').style.display='';
			} else {	
				$('sub_error').style.display='none';
				$('enteremail').value='';
				$('sub_confirm').innerHTML ='Thank you for subscribing to Kidrobot!';
				$('sub_confirm').style.display='';
			}
		},
		onFailure: function(){ },
		postBody: get_form_values('newsletterform')
	});
}


function submit_job_list_email(url){
	new Ajax.Request(url, {
		method: 'post',
		parameters: { randid: Math.random() },
		onSuccess: function(transport) {
			$('sendfrom_error').hide();
			$('sendto_error').hide();
			$('sendconfirmation').hide();
			
			var text = transport.responseText;
			if (text.indexOf('sendfrom required') >= 0){
				$('sendfrom_error').update('* you must enter an email address');
				$('sendfrom_error').show();
			}
			if (text.indexOf('sendfrom invalid') >= 0){
				$('sendfrom_error').update('* you must enter a valid email address');
				$('sendfrom_error').show();
			}
			if (text.indexOf('sendto required') >= 0){
				$('sendto_error').update('* you must enter an email address');
				$('sendto_error').show();
			}
			if (text.indexOf('sendto invalid') >= 0){
				$('sendto_error').update('* you must enter a valid email address');
				$('sendto_error').show();
			}
			if (text.indexOf('send') == -1){
				$('sendfrom').value = '';
				$('sendto').value = '';
				$('comments').value = '';
				$('sendconfirmation').show();
			}
		},
		onFailure: function(){ },
		postBody: get_form_values('job_list_email_form')
	});
}


