// JavaScript Document - Last modified 25/06/09  - Delphine Lepers


function addParameterToURL(param){
    _url = location.href;
    _url += (_url.split('?')[1] ? '&':'?') + param;
    return _url;
}

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"));																			
					});	
					if(where == 'globalModelSearch'){
						$.ajax({
								type: "GET",
								url: "/support/data/keywords/" +wep.omn.language+"_keywords.xml",
								dataType: "xml",
								success: function(data) {
									$(data).find("kw").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);};
											}
							});							
					}				
				});							
}

	function consentcookies(val){		
			var currentdomain = document.domain.replace('stg','').replace('www','');
			if(val=='true'){
				$.cookie('consent.cookie','true', {  expires: 182, path: '/', domain: currentdomain });	
				console.log(currentdomain);
						parent.location.reload();
			}
			else{
				/*deletecookies();*/
				$.cookie('consent.cookie','false', { path: "/", domain: currentdomain  });		
			}	
	};
	
	//Centralize cookie setting, if user approves cookie.
	function setCookies(name,value,expiration)
	{			
			if(allowCookies){		
				$.cookie(name,value, { expires: expiration, path: "/" });		
			}
	}

	function showPopupCookie()
    {
		var showPopup = false;
		if(env != 'prd'){
		 	if(currentlocale != 'tr_TR' && currentlocale != 'ru_RU' && currentlocale != 'uk_UA' && currentlocale != 'ru_KZ' ){
				showPopup= true;
			}
		}
		return showPopup;
	}
	
	function allowCookies()
    {
        var allowCookie = true;
      
        if(env != 'prd'){
		 	if(currentlocale != 'tr_TR' && currentlocale != 'ru_RU' && currentlocale != 'uk_UA' && currentlocale != 'ru_KZ' ){
			
			allowCookie = $.cookie('consent.cookie') ? $.cookie('consent.cookie') : '';	
			}
		}

        return allowCookie;
    }
	
	function deletecookies(){
		var cookies = document.cookie.split(';');
		for (var i = 0; i < cookies.length; i++)
		{
			var c = cookies[i].split('=');
		$.cookie(c[0], '', {expires:0,path:"/"});
		//console.log('delete ' + c[0]);
		}	
	}

/*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.toLowerCase();
	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('');
			setCookies('serialNumber','',365);
			setCookies('productCode','',365);
			setCookies('modelId','',365);
		/*	$.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');
				//console.log('send_serial return false');
				}
				
			return false;
	}else{
			$('#sn').removeClass('invalid');
			$('#sn').addClass('valid');
			var pc = $('#pc').val();
			var sn = $('#sn').val()
			//$.cookie('serialNumber',$('#sn').val(), { duration: 365, path: "/" });
	
			setCookies('productCode', $('#pc').val(),365);
			setCookies('serialNumber', $('#sn').val(),365);
			
			/*console.log(pc);
			console.log(sn);
			console.log('send_serial return true');*/
			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();
	console.log('check_serial');
	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: "/" });*/
					/*setCookies('modelId',modelname,365);				
					console.log(sn);
					console.log(pc);
					console.log('check_serial');*/
					/* valid input styling */
					setCookies('productCode', pc,365);
					setCookies('serialNumber', sn,365);
					setCookies('modelname', modelname,365);
				
					$('#pc').removeClass('invalid');
					$('#divpc').removeClass('errorField').find('p').remove();
					$('#pc').addClass('valid');					
					if($('#contactsubmit')){$('#contactsubmit').removeAttr('disabled')};
					if($('#model').length != '0'){$('#model').val(modelname);};
				}else { 
					$('#pc').addClass('invalid');
					if($('#contact-find')){$('#divpc').removeClass('errorField').find('p').remove(); $('#divpc').append(invalidsn).addClass('errorField')};
					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, '_self', '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, '_self', '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();
		 $('#contact-serial').show(); $('#contact-find').show(); 
		
	//	$('#pc').addClass('validate[required,length[8,8],custom[validpc]]');
		$('#pc').addClass('validate[required,custom[pc]]');
		//$('#sn').addClass('validate[required,length[7,7]]');
		$('#sn').addClass('validate[required,custom[sn]]');
		$('#pc').validationEngine();
		$('#sn').validationEngine();
    }	
    else 
    {       
        $(' #divpc #pc').removeClass('validate[required,custom[pc]]');
        $('#divsn #sn').removeClass('validate[required,custom[sn]]');
		//$('#divsn').hide(); $('#divpc').hide();
		$('#contact-serial').hide(); $('#contact-find').hide();
    }

  if ($('#questCat').val() == 'PostSales')
	{
		 $('#div-model').show();
		 $('#model').show().addClass('validate[required]');
	}
	else
	{
		$('#div-model').hide();
		$('#model').hide().removeClass('validate[required]');
	}
}

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);
		$('#mob1').addClass('validate[required,minCheckbox]');	
		$('#custPhone').addClass('validate[required]');		
			
    }
    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 country_change2() {
        prefix2 = $("#country2").val().substring(3);
        phone_prefix2 = $(".phone_prefix2");
        if (prefix2 == "39") return_prefix2 = "0039";
        else if (prefix2 == "00" || prefix2 == "") return_prefix2 = "00";
        else return_prefix2 = "00" + prefix2 + "(0)";
        phone_prefix2.val(return_prefix2);
			$('#mob2').addClass('validate[required,minCheckbox]');	
		$('#custPhone2').addClass('validate[required]');	
	
    }
    function country_other2() {
        country2 = $("#country2").val();
        if (country2 == "00-00") {
            $("#country2").val("");
            $("#country_message2").removeClass('vsp-hidden').addClass('vsp-right');
        }
        else {
            $("#country_message2").removeClass('vsp-right').addClass('vsp-hidden');
        }
        if (country2 == "IE-353") $("#postalCode").val(" ");
    }
  function checkForm(form)
  {  
  var empty = /\s/;
 
  // if (!empty.test(form.serial.value))
   if (form.serial.value == "")
   {
	   
      selectmsg = "Serial number is empty";   
	  var newAlert = $('<div class="alert-content" title="Warning"> ' + selectmsg + ' </div>');
      $('#validate-warr').after(newAlert);
      $(newAlert).MsgAlert({autoClose: true, wait: false, className: 'conditions_warning'});
      
	  $('#validate-warr').addClass('notifyError');
      form.serial.focus();
      return false;
    }
   else if(!regex_nr.test(form.serial.value)) 
   {
      selectmsg = "Error: serial format is not valid!";
	  var newAlert = $('<div class="alert-content" title="Warning"> ' + selectmsg + ' </div>');
      $('#validate-warr').after(newAlert);
      $(newAlert).MsgAlert({autoClose: true, wait: false, className: 'conditions_warning'});
      $('#validate-warr').addClass('notifyError');
      form.serial.focus();
      return false;
    }
    else
    {
      return true;
    }   
	
  }  



//    function calendar() {
//        alert('');
//        $('document').ready(function () {
////            $('#contactfrm').validationEngine();
//            $("#deliveryDate").datepicker({
//                hideIfNoPrevNext: true,
//                dateFormat: 'dd-mm-yy',
//                beforeShowDay: $.datepicker.noWeekends,
//                firstDay: 1
//            });
//        })
//    
//    }
