// jquery.jsonp 2.0.2 (c)2010 Julian Aubourg | MIT License
// http://code.google.com/p/jquery-jsonp/
(function(e,b){function d(){}function r(z){c=[z]}function m(z){f.insertBefore(z,f.firstChild)}function l(B,z,A){B&&B.apply(z,A)}function k(z){return/\?/.test(z)?"&":"?"}var n="async",p="",x="error",q="_jqjsp",u="on",o=u+x,a=u+"load",i=u+"readystatechange",w="removeChild",g="<script/>",t="success",v="timeout",f=e("head")[0]||document.documentElement,s={},j=0,c,h={callback:q,url:location.href};function y(z){z=e.extend({},h,z);var N=z.complete,B=z.dataFilter,J=z.callbackParameter,O=z.callback,D=z.cache,F=z.pageCache,A=z.url,I=z.data,M=z.timeout,L,H=z.beforeSend,G=0,E=d;z.abort=function(){!G++&&E()};if(H&&(H(z,z)===false||G)){return z}A=A||p;I=I?((typeof I)=="string"?I:e.param(I,z.traditional)):p;A+=I?(k(A)+I):p;J&&(A+=k(A)+escape(J)+"=?");!D&&!F&&(A+=k(A)+"_"+(new Date()).getTime()+"=");A=A.replace(/=\?(&|$)/,"="+O+"$1");function K(P){!G++&&b(function(){E();F&&(s[A]={s:[P]});B&&(P=B.apply(z,[P]));l(z.success,z,[P,t]);l(N,z,[z,t])},0)}function C(P){!G++&&b(function(){E();F&&P!=v&&(s[A]=P);l(z.error,z,[z,P]);l(N,z,[z,P])},0)}F&&(L=s[A])?(L.s?K(L.s[0]):C(L)):b(function(Q,P,R){if(!G){R=M>0&&b(function(){C(v)},M);E=function(){R&&clearTimeout(R);Q[i]=Q[a]=Q[o]=null;f[w](Q);P&&f[w](P)};window[O]=r;Q=e(g)[0];function S(T){T=c;c=undefined;T?K(T[0]):C(x)}Q[i]=function(){/loaded|complete/.test(Q.readyState)&&S()};Q[o]=Q[a]=S;e.browser.opera?((P=e(g)[0]).text="jQuery('#"+(Q.id=q+j++)+"')[0]."+o+"()"):Q[n]=n;Q.src=A;m(Q);P&&m(P)}},0);return z}y.setup=function(z){e.extend(h,z)};e.jsonp=y})(jQuery,setTimeout);
// End of jquery-jsonp

//Show and Hide admiral sports channels
var FW = FW || {};

FW.settings ={
      Admiral : 'on'
};

function freeviewOnload(){                          
                $(".error").hide();
                $('.showChecker').click(function(){
                     var freeviewForm = $('.freeviewForm');
                     freeviewForm.toggleClass('hidden');
                     $(this).parents('li').toggleClass('active');
                     return false;     
                });
}

function validateForm(){
		var validFields = $("#freeviewForm input");
		
		var validHouse = false;
		var validPost = false;
		var valid = false;
		
		$(validFields).each(function(){
				var fieldAttr = $(this).val();
				var errorEl = $(this).parent().find("label.error");
				var fieldName = $(this).attr("name");
				$(this).focus(function(){
						$(errorEl).hide();
						$(this).removeClass("error");
				});
				if(fieldName === "houseNumber"){
						if(fieldAttr !== ""){
								$(this).removeClass("error");
								$(errorEl).hide();
								validHouse = true;
						}
						else{
								$(this).addClass("error");
								$(errorEl).show();
								validHouse = false;
						}
				}
				
				if(fieldName === "postcode"){
						if(fieldAttr !== ""){
								var postcodeVal = /^\s*[A-Z]{1,2}[0-9R][0-9A-Z]? {0,1}[0-9][ABD-HJLNP-UW-Z]{2}\s*$/i;
								if (!(postcodeVal.test(fieldAttr))) { 
										$(this).addClass("error");
										$(errorEl).show();
										validPost = false
								 }
								else{
										$(this).removeClass("error");
										$(errorEl).hide();
										validPost = true;
								}	
						}
						
						else{
								$(this).addClass("error");
								$(errorEl).show();
								validPost = false;
						}
				}				
		})
		
		if(validHouse === true && validPost === true){
				valid = true;	
		}
		else{
				valid = false;
		}
		
		return valid;
}

function freeviewFormSubmit(){
		// bind form using ajaxForm

		$('#freeviewCheckBtn').click(function(){ 
				getData();
				return false;
		});
		
		// Added by C.McGinty for keypress
		$('#freeviewCheckBtn').bind('keypress', function(e) {
				if(e.keyCode==13){
						getData();
						return false;
				}
		});	
};

function getData(){
		if(validateForm()){
				var house = $("#FW_houseNumber").val();
				var post = $("#FW_postcode").val();
				$(".channels").remove();
                                
                                var freeviewCheckerLightbox = document.getElementById("lightbox_freeview_checker") 
                                Lightbox.showLightbox(freeviewCheckerLightbox);
                                Lightbox.tintBg();

				getResponse(house,post);
                                
                                $('#close_lightbox_freeview_checker').bind('click', function(){
                                               $('.channel').html('');
                                               $('#switchover').html('');
                                               $('#tempInfo').remove();
                                               $('#freeviewLightbox h4').remove();
                                               $('.channelContent').removeClass('hidden');
                                });
                                
				return true;
		}
		else{
			return false;
		}
		
};

function getResponse(houseNumber, postCode){
		var genURL = "http://www.btvisionpc.bt.com/webservice/forecast/results/postcode/"+ postCode + "/house/" + houseNumber + "/exact_match/no/";

                $.jsonp({
			url : genURL,
                        dataType: 'jsonp',
                        timeout : 30000,
                        type: 'GET',
                        beforeSend : function(){
                                $('#freeviewLightbox').addClass('loading');
                                $(".channelContent").addClass('hidden');    
                                 $(".switchInfo").addClass('hidden');
                                $(".errorResult").remove();
                               
                        },
			complete : function () {
                                $('#freeviewLightbox').removeClass('loading');
			},
                        error : function(xOptions, textStatus){
                                if(textStatus == 'timeout'){        
                                                var errorMsg = '<div class="errorResult">' + 'Sorry, a technical error has occurred. Please attempt to check your freeview again.' + '</div>';
                                                $('#freeviewLightbox').prepend('errorMsg');
                                                $('#freeviewLightbox').removeClass('loading');
                                }
                        }
		});               
}

function webservice_pcd_callback(obj){
                //check status
                var errorCode =  obj.response.status;
        
                if( (errorCode < 0) || (errorCode > 2)){
                                $('#freeviewLightbox').prepend('<div class="errorResult">' + errorMessageLookup(errorCode) + '</div>');           
                                return false;
                }
               
                var data = obj.response.channel_list.current;
                var channelType = 3;
                var channelName = ['premium_available', 'available', 'unavailable'];
                
                
                var premiumHeading = "<h5><span id='pcNum1'>" + data.premium_available.count + " </span>premium channels</h5>";
                var availableHeading = "<h5>" + data.available.count + " available freeview channels</h5>";
                var unavailableHeading = "<h5>" + data.unavailable.count + " unavailable channels</h5>";
                var headingName = [premiumHeading, availableHeading, unavailableHeading];
                var availableNum = data.premium_available.count + data.available.count;
                var heading = "<h4>Good news. You can receive <span id='pcNum2'>" + availableNum + "</span> Freeview channels</h4><p id='tempInfo'>Sky Sports 1, Sky Sports 2 and ESPN are premium channels. If you don't see them below, they are unavailable.</p>";
                var sum = 0; //total numbur for premium channel not including admiral channels
                
                var switchover = "The digital switchover: " + obj.response.switchover;
                
                if(availableNum == 0){
                     heading = "<h4 id='tempInfo'>Sky Sports 1, Sky Sports 2 and ESPN are premium channels. If you don't see them below, they are unavailable.</h4>";           
                }
                
                $('.channelContent').prepend(heading);
                
                for (i=0 ; i < channelType; i++){
                     var channel = data[channelName[i]].channels;
                     var channelElem = $('.' + channelName[i] + 'ContList');
                                    
                     channelElem.prepend(headingName[i]); 
                     
                     if(channelElem.find('ul').length == 0){
                           var channelList = document.createElement("ul");
                              $(channelList).appendTo(channelElem);                   
                     }else{
                           var channelList = channelElem.find('ul');
                               channelList.html('');
                     }
                     
                     if(channel.length !== 0){
                           var total = channel.length;
                           var list = "";
                           
                                if(i == 2 ){    //only show name for unavailable channel
                                                for (j=0; j < total; j ++){
                                                     var listNum = j + 1;
                                                     var name = channel[j].name;
                                                     list += '<li><span>' + listNum + '. </span>' + name + '</li>';
                                                 }          
                                }else{
                                                for (j=0; j < total; j ++){
                                                     var name = channel[j].name;
                                                     var imageurl = channel[j].imageurl;
                                                     
                                                     if(i == 0){ //for premium channel show channal name
                                                                if((FW.settings.Admiral == "off") && ((name == 'Sky Sports 1') || (name == 'Sky Sports 2'))){
                                                                }else{
                                                                                list += '<li><img src="' + imageurl + '" alt="' + name + '"/><p>' + name + '</p></li>';
                                                                                sum += 1;
                                                                }
                                                     }else{
                                                                list += '<li><img src="' + imageurl + '" alt="' + name + '"/></li>';
                                                     }
                                                }
                                }
                           $(channelList).html(list);   
                     }
                };
                
                if(FW.settings.Admiral == "off"){
                     var newTotal = data.available.count + sum;
                     $("#pcNum1").text(sum + ' ');
                     $("#pcNum2").text(newTotal + ' ');
                }
                
                $('#switchover').html(switchover);
                $(".channelContent").removeClass('hidden');
                $(".switchInfo").removeClass('hidden');
                
};

function errorMessageLookup(errorCode){
        var error = "";
        
        switch(errorCode)
        {
        case 2:
            error = "The postcode is valid but we have no address string and exact match is required";
            break;
        case -1:
            error = "No PCD data available";
            break;
        case -2:
            error = "The postcode you have entered does not currently have any information available. Please check back at a later date.";
            break;
        case -3:
            error = "The postcode you have entered is a PO BOX address so we cannot provide meaningful information.";
            break;
        case -5:
            error = "The postcode and address are valid but nothing is in the database.";
            break;
        case -7:
            error = "Unable to contact database, please try again later.";
            break;
        case -8:
            error = "The exact_match parameter must be yes or no";
            break;
        case -9:
            error = "The postcode you have entered is outside the area that we currently have information available for. Please check back at a later date.";
            break;
        case -10:
            error = "Internal error.";
            break;
        case -11:
            error = "I expected a pixel ID but didn't receive one.";
            break;
        case -12:
            error = "The pixel ID is not in the database.";
            break;
        case -22:
            error = "The house name you have entered does not appear to be valid. Please check your house name and try again.";
            break;
        case -24:
            error = "House number/name is required but it's more than 100 characters long";
            break;
        default:
            error = "Sorry please attempt to check your freeview again.";
        }
       
        return error;
};

$(document).ready(function(){
	freeviewOnload();
	freeviewFormSubmit();
 });
