// JavaScript Document - Last modified 25/06/09  - Delphine Lepers

function search_model(where){
			var source_data = new Array();
			$.ajax({
				type: "GET",
				url: "/support/data/models.xml",
				dataType: "xml",
				success: function(data) {
					$(data).find("m").each(function(){
					    source_data.push($(this).attr("id"));
					});
				$("[id$='"+where+"']").autocomplete({
						source: source_data,
						delay:100,
						minLength:2,
						matchSubset:1,
						maxItemsToShow:10,
						select: function(event, ui) { 
						//it's necessary to set the value to the input for the showModelPage function.
							$('#'+where).val(ui.item.value);
							if(where=="show-warr"){showWarranty(where);}
							else if(where!='model' && where!='search-sparrow' ){showModelPage(where);};
						}
				});	
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					//alert(errorThrown);
					}
		});
}
/*used on the compat for NEX page*/
function waitImg(){
	var my_img = new $( 'img' , { 'src' : '/css/imgs/wait.gif'});
	my_img.append($('#compatibilitytab'));
	document.body.style.cursor='wait';
}
function resolvedImg(){
	document.body.style.cursor='default';
}
	
function show_vira(){$('.virs div').eq(0).toggle();}
function show_virb(){$('.virs div').eq(5).toggle();}
///\brief Go to the product page when we enter a model name*/



function rotatenews(current){
		$("#updatebox div").hide();
		$("#updatebox div").eq(current).fadeIn(100);
		$("#updatebox .tabs li").removeClass('active');
		$("#updatebox .tabs li").eq(current).addClass('active');
		
		if(current>=3){
			$("#updatebox .tabs li").hide();
			$("#updatebox .tabs li").slice(3,6).show();
		};
		if(current>=6){
			$("#updatebox .tabs li").hide();
			$("#updatebox .tabs li").slice(6,9).show();
		};		
		if(current>=9){
			$("#updatebox .tabs li").hide();
			$("#updatebox .tabs li").slice(9,12).show();
		};
		if(current>=12){
			$("#updatebox .tabs li").hide();
			$("#updatebox .tabs li").slice(12,15).show();
		};		
		
		current <= $("#updatebox .tabs li").length-1 ? current++ : current =0;

		t=setTimeout('rotatenews('+current+')',5000);

}

function showWarranty(where){
	var theModel = $('#'+ where ).val();
	theModel=theModel.toUpperCase();
	var theURL='';
	var myRequest=$.ajax({
						url: "/support/shared/code/supportwebservs.asmx/getWarrPage?lg="+s.prop3+"&m=" + theModel,
						dataType: "xml",
						success:function(xml,data) {
							theURL=xml.getElementsByTagName( 'string' )[0].childNodes[0].nodeValue; 
							if(theURL.indexOf('computing/vaio/index')==-1){
								if ($.browser.msie){
									
									var referLink = document.createElement('a');
									referLink.href = theURL;
									document.body.appendChild(referLink);
									referLink.click();
								} else {
									$(location).attr('href',"http://"+document.domain+theURL)
								}
							}else{
								
									$(location).attr('href',theURL)
							};
						}						
	});	
;}

function showModelPage(where){
	var theModel = $('#'+ where ).val();
	theModel=theModel.toUpperCase();
	var theURL= "/support/"+wep.locale.substring(0,2)+"/product"+"/"+theModel.replace('/','_');
	if(where=="specs"){theURL+="/specifications"};
	$(location).attr('href',theURL);
;}

///\brief Sends feedback to the database
function storeFBInfoInDB(theRating, theComments ) {
	var myRequest = $.ajax({
							url:'/support/shared/code/supportwebservs.asmx/storeFeedbackData?theLocation=' + escape( document.location ) + '&theRating=' + theRating +'&theComments=' + escape( theComments )  + '&theModel=',
							success:function(xml){
									var txt = xml.getElementsByTagName( 'boolean' )[0].childNodes[0].nodeValue;
									}
						   });
}

///\brief Function used to store the results of the survey in the database. 
function storeSurveyResult(casenr, locale){
	supXp = $("input[name='Q2_1']:checked").val();
	compXp = $("input[name='Q2_2']:checked").val();
	comments = $('#survey_commments200').val();

	var myRequest = $.ajax({
							url: '/support/shared/code/supportwebservs.asmx/storeNPSSurveyData?locale=' + locale +'&CaseNumber='+ casenr + "&SupportExperience=" + supXp+'&CompleteExperience='+compXp+'&Comments='+escape(comments),
							success:function(xml){
							var txt = xml.getElementsByTagName( 'boolean' )[0].childNodes[0].nodeValue;
									}
						   });	

	}

/************GLOSSARY SCRIPT*************************/

function show_definition(){
	var content=$(this).next("dd").html();
	alert(content);
	}

/****************** VAIO SCRIPTS in GENESIS ********************/

	function collapseall() {
		$('#varnew1').hide();
		$('#varnew2').hide();
		$('#varnew3').hide();
	}
	function expandall() {
		$('#varnew1').show();
		$('#varnew2').show();
		$('#varnew3').show();
	}
	function switchMenu(obj) {
		var el = $('#'+obj);
		el.toggle();
	}
	
//changing the language of the repair survey
function change_lang(){
	newur = document.location.href;
	document.location.href.match(/\/ru\//)? newur = document.location.href.replace(/\/ru\//,"/en/"):window.location = newur;
	document.location.href.match(/\/en\//)? newur = document.location.href.replace(/\/en\//,"/ru/"):window.location = newur;
	window.location = newur;
}

/* Fill in the product code if the user returns. Make it readonly */
function feed_serial(){

		var pc = $.cookie('productCode') ? $.cookie('productCode') : '';
		var sn = $.cookie('serialNumber') ? $.cookie('serialNumber') : '';
		var modelId = $.cookie('modelId') ? $.cookie('modelId') : '';
		$('#sn').val(sn);
		$('#pc').val(pc);
		$('#model').val(modelId);
		
		/* Add a reset link that empties the cookies and input. */
		if($('#empty-it').length!='0') {var emptybtn = $('<a class="submit" id="change_serial"> &nbsp; &nbsp; or '+ empty_msg +'</a>');
			if(sn!='' || pc!=''){$('#empty-it').append(emptybtn);};
		};
		$('#empty-it').bind('click', function(e){
			$('#sn').removeAttr('readonly');
			$('#pc').removeAttr('readonly');
			$('#pc').val(''); $('#sn').val('');
			$.cookie('serialNumber','', { duration: 365, path: "/" });
			$.cookie('productCode', '', { duration: 365, path: "/" });
			$.cookie('modelId', '', { duration: 365, path: "/" });
		})
}

function send_serial(){
	/*A field is invalid or sn is less than 7 - Don't submit*/
	if($('.invalid').length!='0' || $('#sn').val().length!='7'){
			if($('#sn').val().length!='7'){$('#sn').addClass('invalid')}else{
				$('#sn').removeClass('invalid');
				$('#sn').addClass('valid');
				}
				
			return false;
	}else{
			$('#sn').removeClass('invalid');
			$('#sn').addClass('valid');
			$.cookie('serialNumber',$('#sn').val(), { duration: 365, path: "/" });
			return true;
	}
	
}

function check_regex(regex_nr){
  $("#serial").removeClass('valid').removeClass('invalid');
  if($("#serial").val().match(regex_nr)) {$("#serial").addClass('valid').removeClass('invalid'); $("#send-request").removeAttr('disabled');}else{$("#serial").addClass('invalid').removeClass('valid'); };
}


/* check if the serial is valid when user is typing in */
function check_serial(){
	var pc = $('#pc').val();
	var sn = $('#sn').val();

	var modelname;
	
	if(pc.length==8 && pc.match(/^\d{8}$/)) {
		$('#loading_icon').show();
		/*reset styling*/
		
		$.ajax({
			type: "GET",url: "/support/shared/code/supportwebservs.asmx/getModelName?theProductCode=" + pc,dataType: "xml",
			success: function(data) {
				modelname = $(data).find('string').text();
				$('#loading_icon').hide();
				if (modelname !== "0"){ 
					modelname=modelname.replace('/', '_');
					$.cookie('modelId',modelname, { duration: 365, path: "/" });
            		$.cookie('productCode', pc, { duration: 365, path: "/" });
					$.cookie('serialNumber', sn, { duration: 365, path: "/" });
					/* valid input styling */
					$('#pc').removeClass('invalid');
					$('#pc').addClass('valid');
					if($('#contactsubmit')){$('#contactsubmit').removeAttr('disabled')};
					if($('#model').length != '0'){$('#model').val(modelname);};
				}else { 
					$('#pc').addClass('invalid');
					if($('#contactsubmit')){$('#contactsubmit').attr('disabled', 'disabled')};
				}
  
  
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				$('#loading_icon').hide();
				$('#error_icon').show();
			}
		});

	}
}
	

/*****************videotransfer ********************/
function hideTroubleInfo(){
	var questions = $('.bularw h4');
	var answers = $('.bularw .solu');
	questions.each(function(i){
				answers.eq(i).css('display','none');
				$(this).css('cursor','pointer');
				var status=0;
				$(this).bind("click",function(e){
					if(status==0){
						answers.eq(i).css('display','block');
						$(this).addClass('faq_open');
						status=1;
						_gaq.push(['_trackPageview',  '/FAQ/'+s.prop2+'/'+model_used+'/'+s.pageName.replace(/\s+/g,'')+'/'+(i+1)]);

					}else{
						answers.eq(i).css('display','none');
						$(this).removeClass();
						status=0;
					}
			});
		});
	//answers.eq(1).css('display','block');
	}
	
function hideTroubleCat(){
	var questions = $('h3.troubleshooting');
	var answers = $('.trouble_cat');
	questions.each(function(i){
				answers.eq(i).css('display','none');
				$(this).css('cursor','pointer');
				var status=0;
				$(this).bind("click",function(e){
					if(status==0){
						answers.eq(i).css('display','block');
						status=1;
						_gaq.push(['_trackPageview', '/FAQ/'+s.prop2+'/'+model_used+'/'+s.pageName.replace(/\s+/g,'')+'/'+(i+1)]);

					}else{
						answers.eq(i).css('display','none');
						status=0;
					}
			});
		});

if(answers.size()=='1')answers.eq(0).css('display','block');

	}
function validate_disc(){
	$("INPUT[@name=conditionsbox][type='checkbox']").attr('checked', true)
	}


	
function dnld(loc,height,width,scrollbar) {
	    if ($('#conditionsbox:checked').val() == 'on') {
	        if ($('#backupsol')) {
	            $('#backupsol').show();
	            window.open(loc, 'mywindow', 'width='+width+',height='+height+',scrollbars='+scrollbar);
	            return false;
	        } else {
	            return true;
	        };


	    } else {
			model_popup('page','/support/'+wep.omn.language+'/modal-box/ALL/DISC','842','300',agree,'','Close','','cntAccessoriesModelPopup');
	        return false;
	    };

	}
	/***************** for oca.xslt allow to diplay in choosen language ********************/
function dnldlang(lang,loc,height,width,scrollbar) {
	    if ($('#conditionsbox:checked').val() == 'on') {
	        if ($('#backupsol')) {
	            $('#backupsol').show();
	            window.open(loc, 'mywindow', 'width='+width+',height='+height+',scrollbars='+scrollbar);
	            return false;
	        } else {
	            return true;
	        };


	    } else {
			model_popup('page','/support/'+lang+'/modal-box/ALL/DISC','842','300',agree,'','Close','','cntAccessoriesModelPopup');
	        return false;
	    };

	}
	
function resizeIframe(height){
	heightnr=parseInt(height)+10+'px';
	if($('#support').length!='0')$('#support').attr('height',heightnr);
	if($('#sparrow').length!='0')$('#sparrow').attr('height',heightnr);

  }
  
/*****************for data\news\NWZ_headphones.xml ********************/

function check_wm_serial(model, serial){
	var affected = "Please contact our Customer Information Center, when the headphones supplied with WALKMAN have these symptoms. Sony will replace the damaged headphones with new ones without charge.";
	var not_affected = "Your WALKMAN is not affected by this issue. You can continue enjoying your WALKMAN.";
	var $wm_message = $("#wm_message");
	
	if (serial.length < 7) $wm_message.html("The serial number must contain 7 digits.");
	else if (model == "NWZ-S738F" && serial >= "5000001" && serial <= "5031355") $wm_message.html(affected);
	else if (model == "NWZ-S739F" && serial >= "5000001" && serial <= "5014255") $wm_message.html(affected);
	else $wm_message.html(not_affected);
}

/*************** temp for Vaio downlaods - should not use accordeon because of spacing issues **************************/
function toggleDiv(divId) {
   $("#"+divId).toggle();
}

/*************** for email.xslt  - show serial numer field on condition **************************/
function showhidesn(select) {
    var sn = $('#sn');
    var pc = $('#pc');

    if ($('#questCat').val() == 'PostSales' && ($('#prodCat').val() == 'VAIO' || $('#prodCat').val() == 'TABLET'))
    {
        $('#divsn').show(); $('#divpc').show();
		$('#pc').addClass('validate[required,length[8,8],custom[validpc]]')
		$('#sn').addClass('validate[required,length[7,7]]')
		$('#pc').validationEngine();
		$('#sn').validationEngine();
    }
    else 
    {
        $('#divsn').hide(); $('#divpc').hide();
        $('#pc').removeClass('validate[required,length[8,8]]')
        $('#sn').removeClass('validate[required,length[7,7]]')
    }

}

function prefix_change() {
    prefix = $("#prefix").val();
    phone_prefix = $("#phone_prefix");
    if (prefix == "39") return_prefix = "0039";
    else if (prefix == "00" || prefix == "") return_prefix = "00";
    else return_prefix = "00" + prefix + "(0)";
    phone_prefix.val(return_prefix);
}


function onchange(event) {
    country_change();
    country_other();
}

    function country_change() {
        prefix = $("#country").val().substring(3);
        phone_prefix = $("#phone_prefix");
        if (prefix == "39") return_prefix = "0039";
        else if (prefix == "00" || prefix == "") return_prefix = "00";
        else return_prefix = "00" + prefix + "(0)";
        phone_prefix.val(return_prefix);
    }
    function country_other() {
        country = $("#country").val();
        if (country == "00-00") {
            $("#country").val("");
            $("#country_message").removeClass('vsp-hidden').addClass('vsp-right');
        }
        else {
            $("#country_message").removeClass('vsp-right').addClass('vsp-hidden');
        }
        if (country == "IE-353") $("#postalCode").val(" ");
    }

function validateWarr(){
	if($("#serial").val().match(regex_nr)){
		alert('');
	    return true;
   }else{
    	return false;
   }
}



//    function calendar() {
//        alert('');
//        $('document').ready(function () {
////            $('#contactfrm').validationEngine();
//            $("#deliveryDate").datepicker({
//                hideIfNoPrevNext: true,
//                dateFormat: 'dd-mm-yy',
//                beforeShowDay: $.datepicker.noWeekends,
//                firstDay: 1
//            });
//        })
//    
//    }

