$(document).ready(function()
{
	loadOffersOnAjaxRequest();
	function contact() {
		if ($("#contactForm").is(":hidden")){
			$("#contactForm").slideDown("slow");
			//$("#backgroundPopup").css({"opacity": "0.7"});
			$//("#backgroundPopup").fadeIn("slow"); 
		}
		else{
			$("#contactForm").slideUp("slow");
			//$("#backgroundPopup").fadeOut("slow");  
		}
	}
	 
	//run contact form when any contact link is clicked
	$(".contact").click(function(){contact()});
	
	//animation for same page links #
	$('a[href*=#]').each(function() {
		if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
		&& location.hostname == this.hostname
		&& this.hash.replace(/#/,'') ) {
		  var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']');
		  var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
			if ($(this.hash).length) {
				$(this).click(function(event) {
					var targetOffset = $(this.hash).offset().top;
					var target = this.hash;
					event.preventDefault();			   
					$('html, body').animate({scrollTop: targetOffset}, 500);
					return false;
				});
			}
		}
	});
});
function searchKeywords(keywords,pt)
{
    $('#searchTextBox').val(keywords);
    $('#searchKeywordsForm').submit();
}

String.prototype.trim = function ()
{
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

function showList()
{
    $("#suggest1").focus().autocomplete(arr);
}

Array.prototype.unique = function()
{
    var o = {}, i, l = this.length, r = [];
    for(i=0; i<l;i++) o[this[i]] = this[i];
    for(i in o) r.push(o[i]);
        return r;
};

function indexLessThanThousand(element, index, array) {
 return (index < 1000)
}

function forgotPassword()
{
    $('#Inputsubmit').removeAttr("disabled");
    var emailfilter=/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i
    var email=$('#Inputemail').val();
    var emailStatus=emailfilter.test(email);
    if(emailStatus==false)
    {
        alert('This is not a valid email address.');
        return false;
    }
    else
    {
        //$('#InputSubmit').attr("disabled","disabled");
        $('#Inputemail').after("<span id='loadingSpanForEmail'><img src='/images/ajax-loader.gif'></img></span>");
        $('#Emailmessage').html("Sending email...");
        $.post("/ajax",{"action":"forgotPassword","email":email},function(data)
        {
			var status=$(data).find('status').text();
			$('#loadingSpanForEmail').remove();
			alert(status);
        });
		$('#Emailmessage').html("");
    }
}

function addUserItem()
{
    $('#Message').empty();
    var category=$('#ItemAddCategory').val();
    var titletext=$('#ItemAddTitle').val();
    var uniqueidtext=$('#ItemAddUid').val();
    var authtx=$('#ItemAddAuthorText').val();
    var email=$('#ItemAddEmail').val();
	$('#Message').html("Thanks for providing us information about your item.");
	$.post("/ajax",{"action":"ItemAddEmail","email":email,"authtx":authtx,"cat":category,"titletx":titletext,"uidtx":uniqueidtext},function(data)
    {
        var status=$(data).find('status').text();
	});
}
function signUpOnSms()
{
	$('#Button').attr("disabled","disabled");
	$("#erroremail").empty();
	$("#errorphoneno").empty();
	$('#userMessage').empty().remove();
	$('#smsMessage').empty().remove();
	$('#afterButton').empty().remove();
	var emailfilter=/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i
    var phoneFilter=/^([9]{1})([02346789]{1})([0-9]{8})$/;

	var email=$('#inputemail').val();
	var phoneNo=$('#inputphoneno').val();
	var emailVal=emailfilter.test(email);
	var phoneVal=phoneFilter.test(phoneNo);
	if (emailVal==false)
	{
		$("#erroremail").html("Please enter a valid email address.").css({color: "orange"}).show();
	}
    if (phoneVal==false)
	{
		$("#errorphoneno").html("Please enter a valid 10 digit mobile number here.").css({color: "orange"}).show();
	}
	if(emailVal==false || phoneVal==false)
	{
		$('#Button').removeAttr("disabled");
		return false;
	}
	if(emailVal==true && phoneVal==true)
	{
		$('#Button').attr("disabled","disabled");
		$("#inputemail").after("<span id='loadingSpanForEmail'><img src='/images/ajax-loader.gif'></img></span>");
		$("#erroremail").html("Sending email...");
		$("#inputphoneno").after("<span id='loadingSpanForSms'><img src='/images/ajax-loader.gif'></img></span>");
		$("#errorphoneno").html("Sending SMS...");
		//$.post("/ajax?email="+email+"&phoneno="+phoneNo+"&action=signUpOnSms",function(data)
		$.post("/ajax",{"action":"signUpOnSms","email":email,"phoneno":phoneNo},function(data)
		{
            var status=$(data).find('status').text();
            //var userId=$(data).find('status').attr('userId');
			if(status=="Exist")
            {
                $('#erroremail').html("email already exist, please choose another id.");
				$("#errorphoneno").html("");
				$('#Button').after("<div id='userMessage' style='color:orange;font-family:verdana;font-weight:bold;font-size:12px;'>If you are seeing here message like 'email already exist' that means  you have already<br/>registered with us but may be possible you have not yet activated your account.<br/>If this, then go through your mailbox and click the activation link to activate account</div>");
				$('#loadingSpanForEmail').remove();
				$('#loadingSpanForSms').remove();
				$('#Button').removeAttr("disabled");
                return false;
            }
            else
            {
				$("#erroremail").html("");
				$("#errorphoneno").html("");
				$('#Button').after("<div id='smsMessage' style='color:orange;font-family:verdana;font-weight:bold;font-size:12px;'><br/>We have sent you a SMS containing authorization Code.<br/>Please enter the same below.</div>");
				var htmlStr="<div id='afterButton'><br/><input id='userId' type='hidden' /><input id=\"authField\" type=\"text\" value=\"enter authorization code\" onfocus=\"$(this).val('')\"/>&nbsp;&nbsp;&nbsp;&nbsp;<input id='VerifyNow' type=\"button\" value=\"Verify Now\" onclick=\"javascript:verifyPhone($('#authField').val());\"></div><br/><span id=\"ErrorVerify\"></span><br/>";
				$('#smsMessage').after(htmlStr);
				$('#userId').val($(data).find('status').attr('userId'));
				$('#loadingSpanForEmail').remove();
				$('#loadingSpanForSms').remove();
            }
			//$('#Button').removeAttr("disabled");
		});
	}
}
function requestForEnvelopes()
{
	$("#requestEnvelops").empty();
	$("#requestEnvelops").append("<img src='/images/myaccount/requestOver.gif'></img>");
	$("#requestEnvelops").after("<span id='loadingSpan'><img src='/images/ajax-loader.gif'></img></span>");
	document.location.href="/suggestions?action=envelopesRequest";
}
function verifyPhone(authCode)
{
    $('#VerifyNow').attr("disabled","disabled");
    var userId=$('#userId').val();
	$("#authField").after("<span id='loadingSpan'><img src='/images/ajax-loader.gif'></img></span>");
	$('#ErrorVerify').html("Verifying Authorization Code...");
    //$.get("/ajax?userId="+$('#userId').val()+"&authCode="+authCode+"&action=verifyAuthCode",function(data)
	$.post("/ajax",{"userId":$('#userId').val(),"authCode":authCode,"action":"verifyAuthCode"},function(data)
    {
        var verificationStatus=$(data).find('status').text();
        var userId=$(data).find('status').attr('userId');
        var authCode=$(data).find('status').attr('authCode');
        var password=$(data).find('status').attr('password');

        if(verificationStatus=='true')
        {
            $('#failVerificationMessage').empty().remove();
			$('#ErrorVerify').html("");
            $('#VerifyNow').after("<div id='successVerificationMessage'><br/><span style='color:orange;font-family:verdana;font-weight:bold;font-size:12px;'><img src='/images/homepage/arrow.png' />Congratulations! You have verified your phone number to receive FlipGraph alerts.<br/><img src='/images/homepage/arrow.png' />You have got 20 flips for free! <br/><img src='/images/homepage/arrow.png' />Your password has been sent in SMS as well.</span></div>");
			$('#loadingSpan').remove();
        }
        else if(verificationStatus=='false')
        {
			$('#successVerificationMessage').empty().remove();
			$('#ErrorVerify').html("");
            $('#VerifyNow').after("<div id='failVerificationMessage'><br/><span style='color:orange;font-family:verdana;font-weight:bold;font-size:12px;'>You have entered wrong authorization code.Please try again</span></div>");
			$('#loadingSpan').remove();
			$('#VerifyNow').removeAttr("disabled");
        }
    });
}

function changePassword()
{
    $('#updateButton').attr("disabled","disabled");
	//$('#passwordDiv').empty().remove();
	var oldPassword=$('#oldPassword').val();
	var newPassword=$('#newPassword').val();
	var confirmPassword=$('#confirmPassword').val();
	$.post("/ajax",{"action":"changePassword","old":oldPassword,"new":newPassword,"confirm":confirmPassword},function(data)
    {
      //$('#updateButton').after("<div id='passwordDiv' style='font-family:verdana;font-weight:bold;color:orange;'><br/></div>");
        $('#passwordMessage').html($(data).find('status').text());
		$('#updateButton').removeAttr("disabled");
	});
}
function editProfile()
{

	document.UpdateUserProfile.submit();
	/*var email=$('#email').val();
	var firstName=$('#firstName').val();
	var lastName=$('#lastName').val();
	var nickName=$('#nickName').val();
	var addressLine1=$('#address1').val();
	var addressLine2=$('#address2').val();
	var city=$('#city').val();
	var state=$('#state').val();
	var country=$('#country').val();
	var zipcode=$('#zipcode').val();
	var mobileNumber=$('#mobileNumber').val();
	$.post("/ajax",{"action":"editProfile","firstName":firstName,"lastName":lastName,"nickName":nickName,"address1":addressLine1,"address2":addressLine2,"city":city,"state":state,"country":country,"zipcode":zipcode,"mobileNumber":mobileNumber},function(data)
    {
        $('#updateProfileMessage').html($(data).find('status').text());
	});*/
}

function checkEmailAndPhone()
{
	$('#Error').html('');
	$('#ErrorEmail').remove();
    $('#InputButton').after("<div id='ErrorEmail'></div>");
	var emailfilter=/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i
    var phoneFilter=/^([9]{1})([234789]{1})([0-9]{8})$/

	var email=$('#InputEmail').val();
	var phoneNo=$('#InputPhoneNo').val();
	var emailVal=emailfilter.test(email);
	var phoneVal=phoneFilter.test(phoneNo);
	if (emailVal==false)
	{
		$('#ErrorEmail').remove();
		alert("Please enter a valid email address.");
	}
//	else
//	{
//		checkEmail(email);
//	}
    if (phoneVal==false)
	{
		$('#ErrorEmail').remove();
		alert("Please enter a valid 10 digit mobile number here.");
	}
	if(emailVal==false && phoneVal==false)
	{
		return false;
	}
	if(emailVal==true && phoneVal==true)
	{
        $.post("/ajax",{"email":email,"phoneno":phoneNo,"action":"whatsComingNext"},function(data)
		{
            var status=$(data).find('status').text();
			if(status=="Exist")
            {
                $('#ErrorEmail').html("email already exist, please choose another id.");
            }
            else
            {
				$('#ErrorEmail').html(status);
            }
		});
    }
}

function lookup(search)             //for suggestion box list
{
        $().ajaxStart($.unblockUI);
		$().ajaxStop($.unblockUI);
		var productType=$("option:selected").val();
        if(search.length == 0)
        {
			//$('#middleSectionBody').css("z-index","0");
            $('#suggestions').hide();
        }
        else
        {
		    $.get("/ajax",{"search":search,"pt":productType,"action":"keywords"},function(data)
            {
				//	$('#middleSectionBody').css("z-index","-99999");
                    $('#suggestions').show();
                    $('#autoSuggestionsList').empty();
                    $("#autoSuggestionsList").append("<ul>");
                    $(data).find('title').each(function()
                    {
                        var title=decodeURIComponent($(this).text()).replace(/\+/g,' ');
//                        title=title.replace(/nnn/g,"&");
//                        title=title.replace(/dqdq/g, "\"");
//                        title=title.replace(/ltlt/g, "<");
//                        title=title.replace(/gtgt/g, ">");
//                        title=title.replace(/aposapos/g, "'");
//                        title=title.replace(/perper/g, "%");
//                        title=title.replace(/comacoma/g, ",");
//                        title=title.replace(/hh/g, "-");
//                        title=title.replace(/coloncolon/g, ":");
//                        title=title.replace(/usus/g, "_");

                        var productType=$(this).attr('id');
                        var productId=$(this).attr('class');
                        var imageURL=$(this).attr('src');
                        var source=$(this).attr('source');
                        var uni=$(this).attr('uniqueId');
                        var swatchImage=$(this).attr('swatch');
                        $("#autoSuggestionsList").append("<li uniqueId='"+uni+"' source='"+source+"' src='" + imageURL + "' id='"+ productType +"' class='"+ productId + "'><img src='"+swatchImage+"'/><span id='"+uni+"'>"+title+"</span></li>");
                     });
                    $("#autoSuggestionsList").append("</ul>");
                    if($("#autoSuggestionsList").html().length==0)
                    {
						$('#middleSectionBody').css("z-index","0");
                        $('#suggestions').hide();
                    }
					$("li").click(function()
                    {
                        var title=$(this).attr('uniqueId');
                        fill($('#'+title).text());
                    });
            });
      }
}

function fill(val)          //to fill up the search text field on list click...
{
		$('#middleSectionBody').css("z-index","0");
        //$('.MiddleSearchSectionShowSearchOnButtonClick').remove();
		$('#InputSearch').val(val).select();
		$('#autoSuggestionsList').empty();
        $('#suggestions').hide();
}

function video(id)  //To play youvideo on search results(Search page and ProductDetails page)
{
	$('#'+id).youtube(
		{
			callback:$.youtube.playVideo(id)
		}
	);
}

function displaySearchList(pageid)  //for Search page, display search result
{
    $().ajaxStart(function()
	{
		$.blockUI( { border: 'none',
            padding: '15px',
            backgroundColor: '#000',
            '-webkit-border-radius': '10px',
            '-moz-border-radius': '10px',
            opacity: '.5',
            color: '#fff' } );
	});
	$().ajaxStop($.unblockUI);
    //$.get("/ajax?pgid="+pageid+"&action=subList",
	$.post("/ajax",{"pgid":pageid,"action":"subList"},
		function(data)
		{
			if($(data).find('product').length==0)
			{
				Boxy.load("itemadd.html",{unloadOnHide:true,modal:true});
			}
			else
			{
				displayData(pageid,data);
			}
	   }
    );
}

function getTabsData(product_name)  //for home page Tabs(Getlatest products)
{
    var j=0;
	var productTab=product_name;
	if(product_name=="Movies")
	{
		productTab="DVD";
	}
	if(product_name=="Books")
	{
		productTab="BOOK";
	}
	if(product_name=="Music")
	{
		productTab="MUSIC";
	}
	if(product_name=="Games")
	{
		productTab="GAME";
	}
    $.post("/ajax",{"req":productTab,"action":"latest"}, function(data)
	{
        $(data).find('product').each(function()
        {
            var productName=decodeURIComponent($(this).text()).replace(/\+/g,' ');
            var completeTitle=decodeURIComponent($(this).attr('completeTitle')).replace(/\+/g,' ');
            var imageURL=$(this).attr('mediumImage');
            var type=$(this).attr('productType');
            var unique=$(this).attr('uniqueId');
            var product;
            if(type==1){product="books";}
            else if(type==2){product="dvds";}
            else if(type==3){product="games";}
            else if(type==4){product="music";}
            $('#'+productTab+j).html(productName).show();
            $('#'+productTab+j).attr("href","/product/"+product+"/"+unique+"/"+type+"/"+completeTitle.replace(/ /g,'-'));
            $('#'+productTab+'Url'+j+' img').attr("src",imageURL);
            $('#'+productTab+'Url'+j).attr("href","javascript:Boxy.load('/largeimage.html?url="+$(this).attr('largeImage')+"',{unloadOnHide:'true',modal:'true'})");
            j++;
        });
    });
}

function checkEmail(email)          //checking email at registration page(Registration.jsp)
{
    if(email.length==0)
    {
        $("#ErrorEmail").html("email can't be null").css({color:"red"}).show();
        return false;
    }
    else
    {
        $("#InputEmail").after("<span id='loadingSpan'><img src='/images/ajax-loader.gif'></img></span>");
        //$.get("/ajax?req=" + email+"&action=checkLogin",
		$.post("/ajax",{"req":email,"action":"checkLogin"},
            function(data)
            {
                ajaxresponse=$(data).find('status').text();
                if(ajaxresponse=="Exist")
                {
                    $("#ErrorEmail").html("email already exist, please choose another id.").css({color:"red"}).show();
                    $("#loadingSpan").remove();
                    $("#InputSubmit").attr({ disabled:"disabled"});
                    return false;
                }
                else
                {
                    $("#ErrorEmail").html("").css({color:"green"}).show();
                    $("#InputSubmit").removeAttr("disabled");
                }
                $("#loadingSpan").remove();
            }
        );
    }
	return true;
}

function displayAddItemList(listsize,noOfItemsDisplay)
{
    $('.MiddleSearchSectionShowSearchOnButtonClick').empty().remove();
    $('#Pagination').empty();
    var category=$('#category').val();
    var titletext=$('#TitleText').val();
    var uniqueidtext=$('#UniqueIdText').val();
    var authortext=$('#AuthorText').val();
	if(typeof titletext=='undefined')
		titletext='';
	if(typeof uniqueidtext=='undefined')
		uniqueidtext='';
	if(typeof authortext=='undefined')
		authortext=='';
    $().ajaxStart(function()
	{
		$.blockUI( { border: 'none',
            padding: '15px',
            backgroundColor: '#000',
            '-webkit-border-radius': '10px',
            '-moz-border-radius': '10px',
            opacity: '.5',
            color: '#fff' } );
	});
	$().ajaxStop($.unblockUI);
    $.get("/addItem?cat="+category+"&titletx="+titletext+"&uidtx="+uniqueidtext+"&authtx="+authortext,function(data)
	//$.post("/addItem",{"cat":category,"titletx":titletext,"uidtx":uniqueidtext,"authtx":authortext},function(data)
    {
        listsize=$(data).find('product').length;
		var response=$(data).find('product').text();
        if(response=="Not Found")
        {
            $('#Pagination').hide();
            Boxy.load("/itemadd.html?titletx="+titletext+"&uidtx="+uniqueidtext+"&authtx="+authortext+"&cat="+category,{unloadOnHide:true,modal:true});
        }
        else
        {
			$("#Pagination").pagination(listsize, {
                        num_edge_entries: 2,
                        num_display_entries: 6,
                        items_per_page:noOfItemsDisplay,
                        callback:pageselectCallback
			});
            callback:displaySearchList(id)
        }
    });
}

function selectID()
{
	var item=$("#category").val();
	if(item	=="BOOK")
	{
		$("#uniqueId").empty().append("ISBN");
	}
	if(item	=="MOVIE")
	{
		$("#uniqueId").empty().append("UPC");
	}
	if(item	=="GAME")
	{
		$("#uniqueId").empty().append("UPC");
	}
	if(item	=="MUSIC")
	{
		$("#uniqueId").empty().append("EAN");
	}
}

function selectChar()
{
    var item=$("#category").val();
	if(item	==	"BOOK")
	{
	$("#uniqueChar").empty().append("Author");
	}
	if(item	==	"DVD")
	{
	$("#uniqueChar").empty().append("Director");
	}
	if(item	==	"GAME")
	{
	$("#uniqueChar").empty().append("Studio");
	}
	if(item	==	"MUSIC")
	{
	$("#uniqueChar").empty().append("Artist");
	}
}

function pointsConversion(userPoints)
{
	var pointsToConvert=$("#pointSelect").val();
	var IPoint=parseInt(pointsToConvert);
	var UPoints=parseInt(userPoints);
	if(IPoint>UPoints)
	{
		alert("Sorry! you do not have enough points to convert into flips");

	}
	else
	{
	$('#pointConvert').empty();
	$('#pointConvert').append("<img src='/images/convertpointsover.gif'>");
	document.location.href="/suggestions?action=pointsToFlips&pointsToConvert="+pointsToConvert;
	}
}

function tagSubmit(pageName,pageId,action,productId,productType,uniqueId)
{
	var tagValue=$("#tagTextBox").val();
	if(tagValue=="")
	{
		alert("Please Enter Relevant Tags");
		return false;
	}
	else
	{
		$.post("/ajax",{"action":action,"pn":pageName,"pgid":pageId,"pid":productId,"pt":productType,"uid":uniqueId,"tag":tagValue},function(data)
				{
					var status=$(data).find("status").text();
					alert(status);
				});
	}

}
function sendReminder(emailId,counter)
{
	$("#reminder"+counter).after("<span id='loadingSpan'><img src='/images/ajax-loader.gif'></img></span>");
	$.post("/ajax",{"action":"sendReminder","emailId":emailId},function(data)
	{
	     ajaxresponse=$(data).find('status').text();
	     $("#Error").html(ajaxresponse).show();
	     $("#loadingSpan").remove();

	});
}

function loadCountries()
{
    $('#country').empty();
    $.post("/ajax",{"action":"loadCountries"},function(data)
    {
        $(data).find('country').each(function()
        {
			var countryCode=decodeURIComponent($(this).attr('countryCode')).replace(/\+/g,' ');
            $('#country').append("<option value=\""+countryCode+"\">"+decodeURIComponent($(this).text()).replace(/\+/g,' ')+"</option>");
        });
    });


}
function loadCities(st)
{
    if(typeof st=='undefined')
        st="";
    $('#city').empty();
    var countryCode=$('#country option:selected').val();
    $.post("/ajax",{"action":"selectDistrict","countryCode":countryCode,"stateName":st},function(data)
    {
        $(data).find('city').each(function()
        {
            if($(this).text()=="Not Found")
            {

            }
            else
            {
                $('#city').append("<option value=\""+decodeURIComponent($(this).text()).replace(/\+/g,' ')+"\">"+decodeURIComponent($(this).text()).replace(/\+/g,' ')+"</option>");
            }
        });
        $("#city").children(":eq(0)").attr("selected","true");
    });
}
function loadStates()
{
    $('#state').empty();
    $('#city').empty();
    var countryCode=$('#country option:selected').val();
    $.post("/ajax",{"action":"selectState","countryCode":countryCode},function(data)
    {
        $('#state').append("<option>Select State</option>");
        $(data).find('state').each(function()
        {
            if($(this).text()=="Not Found")
            {
                $('#state').empty();
                loadCities("");
            }
            else
            {
                $('#state').append("<option value=\""+decodeURIComponent($(this).attr('stateCode')).replace(/\+/g,' ')+"\">"+decodeURIComponent($(this).text()).replace(/\+/g,' ')+"</option>");
            }
        });
    });
}

function loadAreas()
{
    var countryCode=$('#country option:selected').val();
    var stateName=$('#state option:selected').html()
    var districtName=$('#city option:selected').val();
    var postalCode=$('#zipCode').val();
    if(typeof stateName=='undefined')
        stateName="";
    if(typeof districtName=='undefined')
        districtName="";
    if(typeof postalCode=="undefined")
        postalCode="";
	$('#postalAreas').empty();
	var suggestBoxHTML  = '';
	document.getElementById('suggestBoxElement').style.visibility = 'visible';
    $.post("/ajax",{"action":"postalAreas","postalCode":postalCode,"countryCode":countryCode,"stateName":stateName,"districtName":districtName},function(data)
    {
        $(data).find('area').each(function()
        {
            if($(this).text()=="Not Found")
            {
				document.getElementById('suggestBoxElement').style.visibility = 'hidden';
            }
            else
            {
				suggestBoxHTML += "<div class='suggestions'>"+decodeURIComponent($(this).text()).replace(/\+/g,' ')+"</div>";
            }
        });
		document.getElementById('suggestBoxElement').innerHTML = suggestBoxHTML;
    });
}

function closeSuggestBox()
{
  document.getElementById('suggestBoxElement').innerHTML = '';
  document.getElementById('suggestBoxElement').style.visibility = 'hidden';
}

function checkAddressInfo()
{
    $('#ErrorAddressLine2, #ErrorCity, #ErrorState, #ErrorCountry, #ErrorZipCode, #ErrorPhoneNo').empty();
    //var pinCodeFilter=/^([1-9])([0-9]){5}$/;
    //var phoneFilter=/^([9]{1})([02346789]{1})([0-9]{8})$/;
    var addressLine1=$('#addressLine1').val().trim();
    var addressLine2=$('#addressLine2').val().trim();
    //var city=$('#city').val().trim();
    //var state=$('#state').val().trim();
    //var country=$('#country').val().trim();
    var phone=$('#phoneNo').val().trim();
    var zipCode=$('#zipCode').val().trim();
	var phoneValidationResult;
    if(addressLine1=='' && addressLine2=='')
    {
        $('#ErrorAddressLine2').html("Please fill up your address.");
    }
    //if(city=='')
    //{
    //    $('#ErrorCity').html("Please fill value for city.");
    //}
    //if(state=='')
    //{
    //    $('#ErrorState').html("Please fill up value for state.");
    //}
    //if(country=='')
    //{
    //    $('#ErrorCountry').html("Please fill up country.");
    //}
    //if(pinCodeFilter.test(zipCode)==false)
    //{
    //    $('#ErrorZipCode').html("Please fill up valid value for Pincode");
    //}
	if(zipCode=='')
	{
		$('#ErrorZipCode').html("Please fill up Pincode/Zipcode.");
	}
    //if(phoneFilter.test(phone)==false)
    //{
    //   $('#ErrorPhoneNo').html("Please fill up valid 10 digit mobile number");
    //}
	if(isNaN(phone))
	{
		$('#ErrorPhoneNo').html("Please enter numeric value only");
		phoneValidationResult=false;
	}
	else
	{
            if(phone.length<10)
            {
                    phoneValidationResult=false;
                    $('#ErrorPhoneNo').html("Please enter valid phone number");
            }
            else
            {
                    phoneValidationResult=true;
            }
	}
    if(zipCode=='' || (addressLine1=='' && addressLine2=='') || phoneValidationResult==false)
    {
        return false;
    }
    else
    {
        return true;
    }
}

function checkOffer()
{
	
	var itemId=$("input[name='itid']:checked").val();
	if(typeof itemId=='undefined')
	{
		alert("Sorry! No offer available for this product now.");
		return false;
	}
	else
	{
		$("#loadingSpan").show();
		$("#offerBuyButton").attr("disabled","disabled");
		$('#buyForm').submit();
	}
}

function requestProduct(action)
{    
    var itemId=$('.offerorSelect:checked').val();
    if(typeof itemId=='undefined')
    {
        alert("Sorry! No offer available for this product now.");
        return false;
    }
    else
    {
        $("#loadingSpan").show();
        $("#"+action).attr("disabled","disabled");
        $.post("/ajax",{"action":action,"itid":itemId},function(data)
        {
            var response=$(data).find('response').text();
            if(response=="Added")
                alert("Your item has been added to your cart.Close this dialog box and click on 'View Cart' button to see your cart items.");
            else if(response=="Not Added")
                alert("Some error occurred. Please try after sometime.");
            if(action=="get_it_now")
                //document.location.href="http://localhost:8080/cart.html";
                document.location.href="/cart.html";
        });
        $("#loadingSpan").remove();
    }
}

function calculateTotalCost()
{
    var checked=$("input[name='checked']:checked").val();
	if(typeof checked=='undefined')
	{
		checked='null';
	}
    var itemId=$("input[name='itid']:checked").val();
	$.get("/ajax?action=calculateTotalCost&itid="+itemId+"&checked="+checked, function(data)
	{
		$('#totalCost').html($(data).find('totalCost').text());
	});
}

function updateAddress()
{
    $('#updateAddressButton').hide();
    $('#updateAddressSubmit').show();
    $('#updateAddressCancel').show();
    $("#addressLine1, #addressLine2, #city, #state, #country, #phoneNo, #zipCode, #addressType").removeAttr("disabled");
    $('#offerBuyButton').attr("disabled","true");
	var addressListSize=$('#addressListSize').val();
	checkAgreement(addressListSize);
}
function updateCancel()
{
    $('#updateAddressButton').show();
    $('#updateAddressSubmit').hide();
    $('#updateAddressCancel').hide();
    $("#addressLine1, #addressLine2, #city, #state, #country, #phoneNo, #zipCode, #addressType").attr("disabled","true");
    $('#offerBuyButton').removeAttr("disabled");
    $('#ErrorAddressLine2, #ErrorCity, #ErrorState, #ErrorCountry, #ErrorZipCode, #ErrorPhoneNo').empty();
	var addressListSize=$('#addressListSize').val();
	checkAgreement(addressListSize);
}

function submitOfferForm()
{
    var condition=$('#condition').val();
    if(condition=="0")
    {
        alert('Please select the condition of the product.');
    }
    else
    {	$("#loadingSpan").show();
		$("#offerBuyButton").attr("disabled","disabled");
        $('#offerForm').submit();
    }
}
//done by nv..... can be refactor with old methods for loading city, state, country
function loadCountriesForAds(isoCode)
{
    $('#countryName').empty();
	//$('#countryName').append("<option value='none'>------Select Country------</option>");
	$('#cityName').attr("disabled",true);
	$('#stateName').attr("disabled",true);
	$('#countryName').after("<span id='loadingSpanForCountry'><img src='/images/ajax-loader.gif'></img></span>");
    $.post("/ajax",{"action":"loadCountries"},function(data)
    {
        $(data).find('country').each(function()
        {
			var countryCode=decodeURIComponent($(this).attr('countryCode')).replace(/\+/g,' ');
			var countryfullName=decodeURIComponent($(this).text()).replace(/\+/g,' ');
			var countryName;
			if(countryfullName.length>15)
			{
				countryName=countryfullName.substr(0,15)+"...";
			}
			else
			{
				countryName=countryfullName;
			}
			if(isoCode==countryCode)
			{
				$('#countryName').append("<option selected='true' value=\""+countryCode+"\" title=\""+countryfullName+"\">"+countryName+"</option>");
				loadStatesForAds(isoCode);
			}
			else
			{
				$('#countryName').append("<option value=\""+countryCode+"\" title=\""+countryfullName+"\">"+countryName+"</option>");
			}

			$('#loadingSpanForCountry').remove();
        });
    });


}
function loadCitiesForAds(st)
{
    if(typeof st=='undefined')
        st="";
    $('#cityName').empty();
	$('#cityName').append("<option value='none'>--Select City--</option>");
    var countryCode=$('#countryName option:selected').val();
	$('#cityName').after("<span id='loadingSpanForCity'><img src='/images/ajax-loader.gif'></img></span>");
    $.post("/ajax",{"action":"selectDistrict","countryCode":countryCode,"stateName":st},function(data)
    {

        $(data).find('city').each(function()
        {
            if($(this).text()=="Not Found")
            {
				$('#cityName').attr("disabled",true);
				$('#loadingSpanForCity').remove();
            }
            else
            {
				$('#cityName').attr("disabled",false);

                $('#cityName').append("<option value=\""+decodeURIComponent($(this).text()).replace(/\+/g,' ')+"\">"+decodeURIComponent($(this).text()).replace(/\+/g,' ')+"</option>");
				$('#loadingSpanForCity').remove();
            }
        });
        $("#cityName").children(":eq(0)").attr("selected","true");

    });
}
function loadStatesForAds(countryCode)
{

    $('#stateName').empty();
    $('#cityName').empty();
	$('#stateName').append("<option value='none'>--Select State--</option>");
	$('#cityName').append("<option value='none'>--Select City--</option>");
    var countryCode=$('#countryName option:selected').val();
	$('#stateName').after("<span id='loadingSpanForState'><img src='/images/ajax-loader.gif'></img></span>");
	$.post("/ajax",{"action":"selectState","countryCode":countryCode},function(data)
    {


        $(data).find('state').each(function()
        {
            if($(this).text()=="Not Found")
            {

				$('#stateName').attr("disabled",true);
				$('#loadingSpanForState').remove();
                loadCitiesForAds("");
            }
            else
            {
				$('#stateName').attr("disabled",false);
				$('#cityName').attr("disabled",true);
				var statefullName=decodeURIComponent($(this).text()).replace(/\+/g,' ');
				var stateshortName;
				if(statefullName.length>12)
				{
					stateshortName=statefullName.substr(0,15)+"...";
				}
				else
				{
					stateshortName=statefullName;
				}
                $('#stateName').append("<option value=\""+statefullName+"\">"+stateshortName+"</option>");
				$('#loadingSpanForState').remove();

            }
        });
    });
}
function loadCountriesForAdsPopUp(isoCode)
{
    $('#country').empty();
	//$('#country').append("<option value='none'>------Select Country------</option>");
	$('#city').attr("disabled",true);
	$('#state').attr("disabled",true);
	$('#country').after("<span id='loadingSpanForCountry'><img src='/images/ajax-loader.gif'></img></span>");
    $.post("/ajax",{"action":"loadCountries"},function(data)
    {
        $(data).find('country').each(function()
        {
			var countryCode=decodeURIComponent($(this).attr('countryCode')).replace(/\+/g,' ');
			var countryfullName=decodeURIComponent($(this).text()).replace(/\+/g,' ');
			var countryName;
			if(countryfullName.length>15)
			{
				countryName=countryfullName.substr(0,15)+"...";
			}
			else
			{
				countryName=countryfullName;
			}
			if(isoCode==countryCode)
			{
				$('#country').append("<option selected='true' value=\""+countryCode+"\">"+countryName+"</option>");
				loadStatesForAdsPopUp(isoCode);
			}
			else
			{
				$('#country').append("<option value=\""+countryCode+"\">"+countryName+"</option>");
			}
			$('#loadingSpanForCountry').remove();
        });
    });


}
function loadCitiesForAdsPopUp(st)
{
    if(typeof st=='undefined')
        st="";
    $('#city').empty();

	$('#city').append("<option value='none'>--Select City--</option>");
    var countryCode=$('#country option:selected').val();
	$('#city').after("<span id='loadingSpanForCity'><img src='/images/ajax-loader.gif'></img></span>");
    $.post("/ajax",{"action":"selectDistrict","countryCode":countryCode,"stateName":st},function(data)
    {
        $(data).find('city').each(function()
        {
            if($(this).text()=="Not Found")
            {
				$('#city').attr("disabled",true);
				$('#loadingSpanForCity').remove();
            }
            else
            {
				$('#city').attr("disabled",false);
                $('#city').append("<option value=\""+decodeURIComponent($(this).text()).replace(/\+/g,' ')+"\">"+decodeURIComponent($(this).text()).replace(/\+/g,' ')+"</option>");
				$('#loadingSpanForCity').remove();
            }
        });
        $("#city").children(":eq(0)").attr("selected","true");
    });
}
function loadStatesForAdsPopUp(countryCode)
{
    $('#state').empty();
    $('#city').empty();
	$('#state').append("<option value='none'>--Select State--</option>");
	$('#city').append("<option value='none'>--Select City--</option>");
    var countryCode=$('#country option:selected').val();
	$('#state').after("<span id='loadingSpanForState'><img src='/images/ajax-loader.gif'></img></span>");
    $.post("/ajax",{"action":"selectState","countryCode":countryCode},function(data)
    {

        $(data).find('state').each(function()
        {
            if($(this).text()=="Not Found")
            {
				$('#loadingSpanForState').remove();
                //$('#state').empty();
				$('#state').attr("disabled",true);
                loadCitiesForAdsPopUp("");
            }
            else
            {
				$('#state').attr("disabled",false);
				$('#city').attr("disabled",true);
				var statefullName=decodeURIComponent($(this).text()).replace(/\+/g,' ');
				var stateshortName;
				if(statefullName.length>12)
				{
					stateshortName=statefullName.substr(0,12)+"...";
				}
				else
				{
					stateshortName=statefullName;
				}

                $('#state').append("<option value=\""+statefullName+"\">"+stateshortName+"</option>");
				$('#loadingSpanForState').remove();
            }
        });
    });
}

function checkAgreement(addressListSize)
{
	if(addressListSize=="0")
	{
		$("#offerBuyButton").attr("disabled","disabled");
	}
	else
	{
		if(document.getElementById("policyCheck").checked==true)
		{
			$("#offerBuyButton").removeAttr("disabled");
		}
		else
		{
			$("#offerBuyButton").attr("disabled","disabled");
		}
	}
}

function displayFilterData()
{
        var filteredText=$("#suggest1").val();
        filteredText=filteredText.replace(/\+/,' ');
        var action=$("#filterAction").val();
        var filterBy=$("#filterBy").val();
        $('.MiddleSearchSectionShowSearchOnButtonClick').empty().remove();
        //$('#Pagination').empty();
        $().ajaxStart(function()
        {
            $.blockUI( { border: 'none',
            padding: '15px',
            backgroundColor: '#000',
            '-webkit-border-radius': '10px',
            '-moz-border-radius': '10px',
            opacity: '.5',
            color: '#fff' } );
        });
        $().ajaxStop($.unblockUI);
        $.post("/ajax",{"filteredText":filteredText,"action":action,"filterBy":filterBy},function(data)
        {
            //$('#Pagination').hide();
            displayData(0,data);
        });
    }

    function displayData(pageid,data)
	{
				var i=0;
				$(data).find('product').each(function()
				{
					var minFlips=$(this).attr('minFlips');
					var currencyConversion=$(this).attr('currencyConversionForOld');
					var minPrice=parseInt(minFlips)*parseInt(currencyConversion);
					var freeshipping_old=$(this).attr('free_shipping_old');
					//alert("free shipping old"+freeshipping_old);
					var shippingChargesForOld=$(this).attr('shippingCharges_old');
					//alert("shipping charges old"+shippingChargesForOld);
					var freeshipping_new=$(this).attr('free_shipping_new');
					//alert("free shiping new "+freeshipping_new);
					var shippingChargesForNew=$(this).attr('shippingCharges_new');
					//alert("shipping charges new "+shippingChargesForNew);
					var completeTitle=decodeURIComponent($(this).attr('completeTitle')).replace(/\+/g,' ');
					var title=decodeURIComponent($(this).text()).replace(/\+/g,' ')
                    var metaDescription=decodeURIComponent($(this).attr('metaDescription')).replace(/\+/g,' ');
					var uniqueId=$(this).attr('uniqueId');
					var productType=$(this).attr('productType');
					var tinyImage=$(this).attr('tinyImage');
					if(tinyImage=='null')
					{
						tinyImage='/images/imagenotavail.gif';
					}	
					var largeImage=$(this).attr('largeImage');
					var id=$(this).attr('id');
					var youtubeVideoId=$(this).attr('youtubeVideoId');
					var attribute=decodeURIComponent($(this).attr('attribute')).replace(/\+/g,' ');
					var original_price=decodeURIComponent($(this).attr('original_price')).replace(/\+/g,' ');;
					var flipgraph_price=decodeURIComponent($(this).attr('flipgraph_price')).replace(/\+/g,' ');;
					var discount=$(this).attr('discount');
					if(attribute.length>20)
					{
						attribute=attribute.substring(0,20)+"...";
					}
					var offerCopiesCount=$(this).attr("offerCopiesCount");
					var newProductCount=$(this).attr("newProductCount");
					var best_seller=$(this).attr("best_seller");
					var latest_release=$(this).attr("latest_release");
					var countryCode=$(this).attr("countryCode");
					var actualShippingForOld;
					var actualShippingForNew;
					if(freeshipping_old=="yes")
					{
						actualShippingForOld="Free Shipping";
					}
					else
					{
						actualShippingForOld=shippingChargesForOld;
						if(countryCode=="GB")
						{
							actualShippingForOld=actualShippingForOld+".00 GBP";
						}
						else
						{
							actualShippingForOld=actualShippingForOld+".00 INR";
						}
					}
					if(freeshipping_new=="yes")
					{
						actualShippingForNew="Free Shipping";
					}
					else
					{
						actualShippingForNew=shippingChargesForNew;
						if(countryCode=="GB")
						{
							actualShippingForNew=actualShippingForNew+".00 GBP";
						}
						else
						{
							actualShippingForNew=actualShippingForNew+".00 INR";
						}
					}
					var product;
					var index;
					if(productType==1){product="books";index="books";}
					else if(productType==2){product="dvds";index="DVD";}
					else if(productType==3){product="games";index="videogames";}
					else if(productType==4){product="music";index="music";}
					var amazonUrl="http://www.amazon.com/gp/search?keywords="+uniqueId+"&index="+index+"&linkCode=qs&tag=flip09-20";
					$('.MiddleSearchSectionShow').show();
					$('#InputSearch').removeClass('SearchTextCss');					
					$('#YoutubeLink').attr("href","javascript:Boxy.load('/video.html?pid="+id+"&pt="+productType+"',{unloadOnHide:true,modal:true});");					
					if(minFlips=='-1')
					{
							$('#minFlips').html('Not Available In Flips&nbsp;');
							$('#minUsedPrice').html('Not Available In INR.');
							$('#getButton').html('<img src=/images/get_small_b.gif>');
							$('#getCurrencyButton').html('<img src=/images/get_small_b.gif>');
					}
					else
					{
						$('#minFlips').html('In <span style=font-size:14px;font-weight:bold;color:#aa0000>'+minFlips+' Flips.</span>&nbsp;');
						if(countryCode=='GB')
						{
							$('#minUsedPrice').html('In <span style=font-size:14px;font-weight:bold;color:#aa0000>'+minPrice+'.00 GBP</span>&nbsp;');
						}
						else
						{
							$('#minUsedPrice').html('In <span style=font-size:14px;font-weight:bold;color:#aa0000>'+minPrice+'.00 INR</span>&nbsp;');
						}						
						$("#shipping").html("Shipping:<span style=font-size:14px;font-weight:bold;color:#aa0000>"+actualShippingForOld+"</span>");
						if($("#userNickName").text()=="")
						{
							$("#getButton").html('<a href=javascript:Boxy.load("/LoginPopUP.jsp?action=addReview&pid='+id+'&pt='+productType+'&pn=Search&uid='+uniqueId+'",{unloadOnHide:true,modal:true});><img src=/images/get_small_g.gif border=0 onmouseover=javascript:$(this).attr("src","/images/login_small_g.gif"); onmouseout=javascript:$(this).attr("src","/images/get_small_g.gif");></a>');
							$("#getCurrencyButton").html('<a href=javascript:Boxy.load("/LoginPopUP.jsp?action=addReview&pid='+id+'&pt='+productType+'&pn=Search&uid='+uniqueId+'",{unloadOnHide:true,modal:true});><img src=/images/get_small_g.gif border=0 onmouseover=javascript:$(this).attr("src","/images/login_small_g.gif"); onmouseout=javascript:$(this).attr("src","/images/get_small_g.gif");></a>');
						}	
						else
						{
							$('#getButton').html('<a href=javascript:Boxy.load("/requestpopup/'+id+'/'+productType+'/'+completeTitle.trim().replace(/ /g,'-')+'/flip'+'",{unloadOnHide:true,modal:true});><img src=/images/get_small_g.gif border=0></a>');
							$('#getCurrencyButton').html('<a href=javascript:Boxy.load("/requestpopup/'+id+'/'+productType+'/'+completeTitle.trim().replace(/ /g,'-')+'/currency'+'",{unloadOnHide:true,modal:true});><img src=/images/get_small_g.gif border=0></a>');
						}
					}
					if((original_price!="0.0" && flipgraph_price!="0.0"))
					{
						if(countryCode=='GB')
						{
							original_price=original_price+"0 GBP";
							flipgraph_price=flipgraph_price+".00 GBP";
						}
						else
						{
							original_price=original_price+"0 INR";
							flipgraph_price=+flipgraph_price+".00 INR";
						}
						
						$('#originalprice').html('Original Price:&nbsp;&nbsp;<del><span>'+original_price+'</span></del>');
						$('#discount').html('Discount:&nbsp;&nbsp;<span style=font-size:14px;font-weight:bold;color:#aa0000>'+discount+'%</span> off ');
						$('#flipgraphprice').html('FlipGraph Price:&nbsp;&nbsp;<span style=font-size:14px;font-weight:bold;color:#aa0000>'+flipgraph_price+'</span>');
						if($("#userNickName").text()=="")
						{
							$('#buyButton').html('<a href=javascript:Boxy.load("/LoginPopUP.jsp?action=addReview&pid='+id+'&pt='+productType+'&pn=Search&uid='+uniqueId+'",{unloadOnHide:true,modal:true});><img src=/images/addtocart_small_g.gif border=0 onmouseover=javascript:$(this).attr("src","/images/login_small_g.gif"); onmouseout=javascript:$(this).attr("src","/images/addtocart_small_g.gif");></a><br/><br/><br/><a href=javascript:Boxy.load("/LoginPopUP.jsp?action=addReview&pid='+id+'&pt='+productType+'&pn=Search&uid='+uniqueId+'",{unloadOnHide:true,modal:true});><img src=/images/buy_small_g.gif border=0 onmouseover=javascript:$(this).attr("src","/images/login_small_g.gif"); onmouseout=javascript:$(this).attr("src","/images/buy_small_g.gif");></a>');
						}
						else
						{
						$('#buyButton').html("<span><form method='post' action='/cart'>"+
                                             "<input type='hidden' name='action' value='add_to_cart'>"+
                                             "<input type='hidden' name='pid' value='"+id+"'>"+
                                             "<input type='hidden' name='pt' value='"+productType+"'>"+
                                             "<input type='hidden' name='item_type' value='new'>"+
                                             "<input type='image' src='/images/addtocart_small_g.gif' border='0'>"+
                                             "</form></span><br/>"+
											 "<span><form method='post' action='/cart'>"+
                                             "<input type='hidden' name='action' value='get_it_now'>"+
                                             "<input type='hidden' name='pid' value='"+id+"'>"+
                                             "<input type='hidden' name='pt' value='"+productType+"'>"+
                                             "<input type='hidden' name='item_type' value='new'>"+
                                             "<input type='image' src='/images/buy_small_g.gif' border='0'>"+
                                             "</form></span>"
											);						
						}	
						$("#shippingNew").html("Shipping:<span style=font-size:14px;font-weight:bold;color:#aa0000>"+actualShippingForNew+"</span>");	
					}
						else{
								$('#originalprice').html('New Copy Not Available');
								$('#discount').html('');
								$('#flipgraphprice').html('');
								$('#buyButton').html('<img src=/images/addtocart_small_b.gif border=0>&nbsp;<img src=/images/buy_small_b.gif border=0>');
								$("#shippingNew").html("");	
								
							}	
					if($("#userNickName").text()=="")
					{
						$("#offerButton").html('<a href=javascript:Boxy.load("/LoginPopUP.jsp?action=addReview&pid='+id+'&pt='+productType+'&pn=Search&uid='+uniqueId+'",{unloadOnHide:true,modal:true});><img src=/images/offer_small_g.gif border=0 onmouseover=javascript:$(this).attr("src","/images/login_small_g.gif"); onmouseout=javascript:$(this).attr("src","/images/offer_small_g.gif");></a>');
						$("#offerCurrencyButton").html('<a href=javascript:Boxy.load("/LoginPopUP.jsp?action=addReview&pid='+id+'&pt='+productType+'&pn=Search&uid='+uniqueId+'",{unloadOnHide:true,modal:true});><img src=/images/offer_small_g.gif border=0 onmouseover=javascript:$(this).attr("src","/images/login_small_g.gif"); onmouseout=javascript:$(this).attr("src","/images/offer_small_g.gif");></a>');
					}	
					else
					{
						$('#offerButton').html('<a href=javascript:Boxy.load("/offerpopup/'+id+'/'+productType+'/'+completeTitle.trim().replace(/ /g,'-')+'/flip'+'",{unloadOnHide:true,modal:true});><img src=/images/offer_small_g.gif border=0></a>');
						$('#offerCurrencyButton').html('<a href=javascript:Boxy.load("/offerpopup/'+id+'/'+productType+'/'+completeTitle.trim().replace(/ /g,'-')+'/currency'+'",{unloadOnHide:true,modal:true});><img src=/images/offer_small_g.gif border=0></a>');
					}
					if(offerCopiesCount=='0'){$('#offerCopiesCount').hide();}
					else if(offerCopiesCount=='1'){$('#offerCopiesCount').html('('+offerCopiesCount+' Copy Available)');}
					else {$('#offerCopiesCount').html('('+offerCopiesCount+' Copies Available)');}
					if(newProductCount=='0'){$('#newCopiesCount').hide();}
						else if(newProductCount=='1'){$('#newCopiesCount').html('('+newProductCount+' Copy Available)');}
						else {$('#newCopiesCount').html('('+newProductCount+' Copies Available)');}					
					if(best_seller=='1' && latest_release=='1')
					{
						$('#plus,#bestSeller,#latestRelease').show();
					}
					else if(best_seller=='1' && latest_release=='0')
					{
						$('#bestSeller').show();
						$('#plus,#latestRelease').hide();
					}
					else if(best_seller=='0' && latest_release=='1')
					{
						$('#latestRelease').show();
						$('#plus,#bestSeller').hide();
					}
					else
					{
						$('#plus,#bestSeller,#latestRelease').hide();
					}
									
					$('#ProductImage').attr("href","/product/"+product+"/"+uniqueId+"/"+productType+"/"+completeTitle.replace(/ /g,'-'));                    
					$('#ProductImage img').attr("src",tinyImage);
					$('#ProductImage img').attr("title",metaDescription);
					$('#Title0').html(title);
					$('#Title0').attr("href","/product/"+product+"/"+uniqueId+"/"+productType+"/"+completeTitle.replace(/ /g,'-'));
					$('#Description0').html(attribute);
					$('#Description0').attr("href","#");
					$('#amazonButton a').attr("href",amazonUrl);
					$('#Buy a').attr("href","/buy/"+id+"/"+productType+"/"+completeTitle.replace(/ /g,'-'));
					$('#Offer a').attr("href","/offer/"+id+"/"+productType+"/"+completeTitle.replace(/ /g,'-'));
					$('#wishList a').attr("href","javascript:Boxy.load('/wishlist.html?action=addToWishList&pn=ProductDetails&pid="+id+"&pt="+productType+"',{unloadOnHide:'true',modal:'true'});");
					$('#addTag a').attr("href","javascript:Boxy.load('/addtag.html?pid="+id+"&pt="+productType+"&action1=addTag&pn=Search&pgid="+pageid+"',{unloadOnHide:'true',modal:'true'});");					
					$('.MiddleSearchSectionShow').clone().attr("class","MiddleSearchSectionShowSearchOnButtonClick").appendTo('.MiddleSearchSection').show();
					$(".MiddleSearchSectionShowSearchOnButtonClick #usedTable").attr("id","usedTable"+i);
					$(".MiddleSearchSectionShowSearchOnButtonClick #newTable").attr("id","newTable"+i).hide();
					$(".MiddleSearchSectionShowSearchOnButtonClick #ownTable").attr("id","ownTable"+i).hide();
					$(".MiddleSearchSectionShowSearchOnButtonClick #used").attr
					(
						{
							id:"used"+i,
							href:"javascript:showAndHide('usedTable"+i+"','newTable"+i+"','ownTable"+i+"');"
							
							
						}	
					);
								
					$(".MiddleSearchSectionShowSearchOnButtonClick #new").attr
					(
						{
							id:"new"+i,
							href:"javascript:showAndHide('newTable"+i+"','usedTable"+i+"','ownTable"+i+"');"
							
						}	
					);
					$(".MiddleSearchSectionShowSearchOnButtonClick #own").attr
					(
						{
							id:"own"+i,
							href:"javascript:showAndHide('ownTable"+i+"','usedTable"+i+"','newTable"+i+"');"
							
						}		
					);					
					//$('.MiddleSearchSectionShowSearchOnButtonClick #MyDiv').attr("id",youtubeVideoId);
					$('#YoutubeLink').show();
					$('#minFlips').show();
					$('.MiddleSearchSectionShow').hide();
					i++;
					if(i==20)
						return false;
			});
    }
	function showOtherTab()
	{
		document.getElementById('oo').style.display='block';
	}
	function hideOtherTab()
	{
		document.getElementById('oo').style.display='none';
	}
	
	function showAndHide(id1,id2,id3,id4)
	{
		
		document.getElementById(id2).style.display="none";
		document.getElementById(id3).style.display="none";
		document.getElementById(id1).style.display="block";
		var x=id1;x=x.split("Table");x=x[0]+x[1];
		var y=id2;y=y.split("Table");y=y[0]+y[1];
		var z=id3;z=z.split("Table");z=z[0]+z[1];
		document.getElementById(x).style.backgroundColor = '#50A029'; 
		document.getElementById(y).style.backgroundColor = '#A0DF82'; 
		document.getElementById(z).style.backgroundColor = '#A0DF82'; 
	}
	
	function checkOfferRadio()
	{
		setTimeout("waitProcess()",250); 
		clearTimeout(0);
	}
	function waitProcess()
	{
		$("input[@id=offerorSelect1]").attr("checked","true");
	}
	function keyPressedForUserLoginPopUp(e)
	{
	var event=e||window.event;
		if(event.keyCode=='13')
				{
					setTimeout("userLoginForPopUp()",100); 
					clearTimeout(0);
				}
		}
	function userLoginForPopUpVerifier()
				{
					//statements to validate the form	
					var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
					var email = $("#email_p").val();
					var password=$("#password_p").val();
					if (!filter.test(email)) 
					{
						
						$("#email-missing_p").show();
						return false;
					}
					else
					{
						
						$("#email-missing_p").hide();
					}
					if (email == "") 
					{
						
						$("#email-missing_p").show();
						return false;
					}
					else
					{
						$("#email-missing_p").hide();
					}		
					if (password == "")
					{
						$("#password-missing_p").show();
						return false;
					} 
					else 
					{
						$("#password-missing_p").hide();
					}	
					return true;
					
				}
				function userLoginForPopUp()
				{
					var check=userLoginForPopUpVerifier();
					if(check==true)
					{
						document.lform.action="/login";
						document.lform.submit();
					}	
				}	
				
function loadOffersOnAjaxRequest()
{
//$("#slidesshowdivforoffers").html("<center><img src='/images/ajax-loader.gif'></center>");
$.post("/ajax",{"action":"currentOffersAjaxFetch"},function(data)
	{
		$("#slidesshowdivforoffers,#output,#offered,#viewMore").empty();
		
		$(data).find('productData').each(function()
		{
			var url=decodeURIComponent($(this).attr('url')).replace(/\+/g,' ');
			var title=decodeURIComponent($(this).attr('title')).replace(/\+/g,' ');
			var productType=$(this).attr('productType');
			var minflips=$(this).attr('minflips');
			var imageUrl=decodeURIComponent($(this).attr('mediumImageUrl')).replace(/\+/g,' ');
			$("#slidesshowdivforoffers").append("<img name='"+url+"' alt='"+title+"$"+productType+"$"+minflips+"'  src='"+imageUrl+"' width='120' height='150' border='0'/>");
		
		});
		$('.slideshow').cycle({
		fx:'fade', 
		timeout: 8000,
		pause:   1,
		before:  onBefore
		//after:   onAfter 
	});
	function onBefore() 
	{
		$(this).css("cursor","pointer");
		$(this).click(function()
		{
			window.location.href=""+this.name+"";
		});
		var nameAndType=(this.alt).split("$");
		var name=nameAndType[0];
		var type=nameAndType[1];
		var offer=nameAndType[2];
		var productTypeStr;
		if(type==1){productTypeStr="books"}
		else if(type==2){productTypeStr="dvds"}
		else if(type==3){productTypeStr="games"}
		else if(type==4){productTypeStr="music"}
		var url="search/"+type+"/"+productTypeStr+"/currentoffers";
			
		
		$('#output').html("<span style='font-family:arial;font-size:12px;color:#093766'><a href="+this.name+" class='offerlink'>" + nameAndType[0] + "</a></span>");
		$('#offered').html("<span style='font-family:arial;font-size:12px;color:#093766'><a href="+this.name+" class='offerlink'> (Offered in <span style='color:#ff0000;font-size:15px;font-weight:bold'>" + nameAndType[2] + " Flips</span>)</a></span>");
		$('#viewMore').html("<br/><span style='font-family:arial;font-size:13px;color:#093766;font-weight:bold'><a href="+url+" class='offerlink'>View More</a></span>");
	}
	});	
	setTimeout("loadOffersOnAjaxRequest()",50000);
}
