/*Code for Homeflow property feed*/
var globalAgentID = "";
var globalBranchId = "";
function getCookie()
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x=="coords")
    {
    return(y);
    }
  }
}

 
function CallFomeFlowForHome() {
   var coords = getCookie();
    //check for cookie//
  var bvalue = false;  
  if(coords != undefined){  
	var ca = coords.split(';');
	var t = ca[0].split("|");
	//check we have value for each coord		
	   for (p = 0;p<=3;p++){
		    if (t[p].length > 0) {
			bvalue = true;
		    }
		    else {
			bvalue = false
			break;
		    }
	}

   } 
    
     var SWlat;
     var SWlng;
     var NElat;
     var NElng;
     if (bvalue) {
         SWlat = t[0];
         SWlng = t[1];
         NElat = t[2];
         NElng = t[3];            
     }
     else {
         var NExcoord = NECoord(530150);
         var NEycoord = NECoord(179550);
         var LtLngNEArr = OSGridToLatLong(NExcoord, NEycoord).split(',');
         var SWxcoord = SWCoord(530150);
         var SWycoord = SWCoord(179550);
         var LtLngSWArr = OSGridToLatLong(SWxcoord, SWycoord).split(',');

          SWlat = jQuery.trim(LtLngSWArr[0]);
          SWlng = jQuery.trim(LtLngSWArr[1]);
          NElat = jQuery.trim(LtLngNEArr[0]);
          NElng = jQuery.trim(LtLngNEArr[1]);        
     }

     var script = document.createElement("script");
     script.type = "text/javascript";
     script.src = "http://api.homeflow.co.uk/v1/?method=search_with_bounds&api_key=688d6514ac696d8a0ef123bc8c631bdc&price_max=1000000&sw_lat=" + SWlat + "&sw_lng=" + SWlng + "&ne_lat=" + NElat + "&ne_lng=" + NElng + "&type=sales&callback=doHomeFlow";    // use this for linked script
     document.body.appendChild(script);
}

function CallHomeFlowScript() {
    var xcoord = CheckXYlength($('#TownXY').val().split(",")[0]);
    var ycoord = CheckXYlength($('#TownXY').val().split(",")[1]);
    var LtLngArr = OSGridToLatLong(xcoord, ycoord).split(',');

    var NExcoord = NECoord(($('#TownXY').val().split(",")[0]));
    var NEycoord = NECoord(($('#TownXY').val().split(",")[1]));
    var LtLngNEArr = OSGridToLatLong(NExcoord, NEycoord).split(',');

    var SWxcoord = SWCoord(($('#TownXY').val().split(",")[0]));
    var SWycoord = SWCoord(($('#TownXY').val().split(",")[1]));
    var LtLngSWArr = OSGridToLatLong(SWxcoord, SWycoord).split(',');

    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "http://api.homeflow.co.uk/v1/?method=search_with_bounds&api_key=688d6514ac696d8a0ef123bc8c631bdc&price_max=1000000&sw_lat=" + jQuery.trim(LtLngSWArr[0]) + "&sw_lng=" + jQuery.trim(LtLngSWArr[1]) + "&ne_lat=" + jQuery.trim(LtLngNEArr[0]) + "&ne_lng=" + jQuery.trim(LtLngNEArr[1]) + "&type=" + getCurrentCat() + "&callback=doHomeFlow";    // use this for linked script
    document.body.appendChild(script);

    //save current lat/lon to cookie for homepage.
    setCookie(jQuery.trim(LtLngSWArr[0]),jQuery.trim(LtLngSWArr[1]),jQuery.trim(LtLngNEArr[0]),jQuery.trim(LtLngNEArr[1]));
}


function CallHomeFlowScriptForAgentsPage(coords) {
    var xcoord = CheckXYlength(coords.split(",")[0]);
    var ycoord = CheckXYlength(coords.split(",")[1]);
    var LtLngArr = OSGridToLatLong(xcoord, ycoord).split(',');

    var NExcoord = NECoord(CheckXYlength(coords.split(",")[0]));
    var NEycoord = NECoord(CheckXYlength(coords.split(",")[1]));
    var LtLngNEArr = OSGridToLatLong(NExcoord, NEycoord).split(',');

    var SWxcoord = SWCoord(CheckXYlength(coords.split(",")[0]));
    var SWycoord = SWCoord(CheckXYlength(coords.split(",")[1]));
    var LtLngSWArr = OSGridToLatLong(SWxcoord, SWycoord).split(',');

 var script = document.createElement("script");
    script.type = "text/javascript";
    var appUrl= "";
    if ($('#hmAgentID').length > 0) { appUrl = $('#hmAgentID').val(); }
    script.src = "http://api.homeflow.co.uk/v1/?method=search_with_bounds&api_key=688d6514ac696d8a0ef123bc8c631bdc&price_max=1000000&sw_lat=" + jQuery.trim(LtLngSWArr[0]) + "&sw_lng=" + jQuery.trim(LtLngSWArr[1]) + "&ne_lat=" + jQuery.trim(LtLngNEArr[0]) + "&ne_lng=" + jQuery.trim(LtLngNEArr[1]) + "&type=" + getCurrentCat() + "&callback=doHomeFlow&agency_foreign_key=" + appUrl;    // use this for linked script
    document.body.appendChild(script);
}

function setCookie(swLat, swLng, neLat, neLng) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + 1);
    document.cookie = "coords=" + swLat + "|" + swLng + "|" + neLat + "|" + neLng + "; expires=" + exdate.toUTCString() + ";domain=email4property.co.uk;path=/"
}

function getCurrentCat() {
    var c = $('#currentCat').val();
    switch (c) {
        case "letting agents":
        case "rent out your property":
            return "lettings"
            break;
        default:
            return "sales"
    };
}

function doHomeFlow(data) {
    //process homeflow data
    var n = data.property_count;
    //get random number so always display different properties on reload.  
    var upperItemCount = n > 1 ? 2 : 0;
    var lowerItemCount = 0;
    
    //var prop = new Array(2);
    var prop = [];
    if (n == 0) {
        //hide properties section
        $('#adverts').hide();

    } else {
        $('#adverts').removeClass('hide_properties');
	    var tempCount = genRandomUppperLimit(data.data.length)
	    if ((tempCount < data.data.length) && (tempCount > 3)) {
		upperItemCount = tempCount;
		lowerItemCount = tempCount - 2;
	    }
	    else
	    {
	    	tempCount == 2 ? upperItemCount = 2 : upperItemCount = 1;
	    }    
	        var t = 0;
	        var ogCount = upperItemCount;
	        for (i = lowerItemCount; i <= upperItemCount; i++) {
		        if (ChecNullValues(data.data[i].photo, data.data[i].beds) && (upperItemCount < data.property_count)) {
		            //no image with property, so get the next one.
		            if (ogCount > 4){
		            upperItemCount = upperItemCount + 1;
		            }
		        }
		        else {
		            prop[t] = new Array(4)
		            prop[t][0] = data.data[i].id;
		            prop[t][1] = data.data[i].photo;
		            prop[t][2] = data.data[i].beds;
		            prop[t][3] = data.data[i].town;
		            prop[t][4] = data.data[i].price;
		            globalAgentID = data.data[i].agency_id;
		            globalBranchId = data.data[i].branch_id;
		            t = t + 1		           
		        }
	        }

	    DisplayData(prop);     
    }
}

function doHomeFlowForBranches(data) {
	for (var key in data) {
	  console.log(data[key]);
	}
}

function ChecNullValues(photo, beds) {
	var sendTrue = 0;
	if (photo == null) { sendTrue = sendTrue + 1   }
	if (beds==0) { sendTrue = sendTrue + 1   }
	if (beds == null) { sendTrue = sendTrue + 1   }  
	if (sendTrue >0){return true}
	else{return false
	};
}

function DisplayData(arr) {
    var properties = "";
    for (i = 0; i < arr.length; i++) {
        var url = "http://property.email4property.co.uk/" + getCurrentCat() + "/" + arr[i][0];
        properties = properties + '<div id=\"ad' + arr[i][0] + '\" class=\"ad\">';
        properties = properties + '<a href=\"' + url + '\"><img width=\"174\" height=\"101\" alt=\"\" src=\"http://www.homeflow.co.uk' + arr[i][1] + '\"></a>';
        properties = properties + '<ul><li><a href=\"' + url + '\">' + arr[i][4] + '</a></li>';
        properties = properties + '<li><a href=\"' + url + '\">' + arr[i][2] + ' Beds</a></li>';
        properties = properties + '<li><a href=\"' + url + '\">' + arr[i][3] + '</a></li>';
        properties = properties + '</ul></div>'
    }
    $('#propertyListing').html(properties);
    $('#homeFlowAgentLink').attr("href","http://property.email4property.co.uk/estate-agents/" + globalAgentID + "/" + globalBranchId)
}

function genRandomUppperLimit(UpperRange) {
    return Math.floor(Math.random() * (parseInt(UpperRange) - 0 + 1)) + 0;
}

function SWCoord(coord) {
    return parseInt(coord) - 2000;
}

function NECoord(coord) {
    return parseInt(coord) + 2000;
}

function CheckXYlength(coord) {
    var i = coord.length
    while (i < 6) {
        coord = coord + "0";
        i = i + 1;
    }
    return coord
}
