
// primary pinpoint
var _pp;
var _map;
var _attractionsArray = [];
var _data = [];
var _infoBox;
var _itineraryArray = [];
var _sv;
function load(){

    _data = get_server_content();
    _sv = new google.maps.StreetViewService();
    
    if (_data['#error']) {
        //alert(response['#data']);        
        _gaq.push(['_trackEvent', 'DataError', response['#data']]);
    }
    else {
        _pp = _data['#data'].pinpoint;
        _itineraryArray[_pp.siteID] = _pp.name;
        _gaq.push(['_trackPageview', _pp.name]);
        if(_pp.yppie != null){
            document.getElementById('pinpointBtn').style.display='Block';
            var yppie = document.getElementById('yppieURL');
            yppie.setAttribute("href",_pp.yppie);
            yppie.innerHTML = _pp.yppie;
            
            var yppieEmail = document.getElementById('yppieEmail');
            yppieEmail.setAttribute("href","mailto:?subject=PinPoint of "+_pp.name+"&body=Click this to view the location: <a href="+_pp.yppie+">"+_pp.yppie+"</a>");
        }
        var latlng = new google.maps.LatLng(_pp.lat, _pp.lng);
        var myOptions = {
            scrollwheel: false,
            zoom: 8,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.TERRAIN
        };
        // V3 of maps api
        _map = new google.maps.Map(document.getElementById("mappanel"), myOptions);
    }
    
    /* 
     not useing an overlay control for itinerary but might use it for something else
     var itineraryControlDiv = document.createElement('div');
     var itineraryControl = new ItineraryControl(itineraryControlDiv, _map);
     itineraryControlDiv.index = 1;
     _map.controls[google.maps.ControlPosition.TOP].push(itineraryControlDiv);
     */
    var myOptions = {
        disableAutoPan: false,
        maxWidth: 350,
        pixelOffset: new google.maps.Size(-155, -220),
        zIndex: null,
        boxStyle: {
            background: " url('./images/bookingInfo_beak.png') no-repeat bottom center", // ,background-position: "center bottom"          
            border: "none",
            width: "320px",
            height: "190px"
        },
        closeBoxMargin: "10px 2px 2px 2px",
        closeBoxURL: "http://yourpinpoints.com/app/WI/images/info_window_close.png",
        infoBoxClearance: new google.maps.Size(1, 1),
        isHidden: false,
        pane: "floatPane",
        enableEventPropagation: false
    };
    _infoBox = new InfoBox(myOptions);
    
    
    
    var primary = new Category("Primary", [_pp]);
    primary.toggleOverlay();
    primary.showBubble();
}

function ShowCategory(category){
    if (_attractionsArray[category] == undefined) {
       _attractionsArray[category] = new Category(category, _data['#data'].attractions.Attractions[category]);
		        
        _gaq.push(['_trackEvent', 'CategoryOverlay', _pp.name, 'category']);
    }
    _attractionsArray[category].toggleOverlay();
}


function Category(category_title, category_data){
    this.category_data = category_data;
    this.category_title = category_title;
    this.shown = false;
    this.markersArray = [];
    
    this.toggleOverlay = function(){
        if (this.shown) {
            this.clearOverlays();
            this.shown = false;
        }
        else {
            this.showOverlays();
            this.shown = true;
        }
    }
    // Removes the overlays from the map, but keeps them in the array
    this.clearOverlays = function(){
        if (this.markersArray) {
            for (i in this.markersArray) {
                this.markersArray[i].setMap(null);
            }
        }
    }
    
    // Shows any overlays currently in the array
    this.showOverlays = function(){
        if (this.markersArray.length == 0) {
            this.setMarkers();
        }
        for (i in this.markersArray) {
            this.markersArray[i].setMap(_map);
        }
    }
    
    this.showBubble = function(){
        for (i in this.markersArray) {
            google.maps.event.trigger(this.markersArray[i], "mouseover");            
        }
    }
    this.addMarker = function(location){
        marker = new google.maps.Marker({
            position: location,
            map: map
        });
        this.markersArray.push(marker);
    }
    // Deletes all markers in the array by removing references to them
    this.deleteOverlays = function(){
        if (this.markersArray) {
            for (i in this.markersArray) {
                this.markersArray[i].setMap(null);
            }
            this.markersArray.length = 0;
        }
    }
    
    this.setMarkers = function(){
        var image;
        var size = new google.maps.Size(18, 24);
        var origin = new google.maps.Point(0, 0);
        var anchor = new google.maps.Point(9, 24);
        
        if (this.category_title == "Beach") {
            image = new google.maps.MarkerImage('images/Beach.png', size, origin, anchor);
        }
        else if (this.category_title == "Birdwatching") {
            image = new google.maps.MarkerImage('images/Birdwatching.png', size, origin, anchor);
        }
        else if (this.category_title == "Castle, monument") {
            image = new google.maps.MarkerImage('images/Castle.png', size, origin, anchor);
        }
        else if (this.category_title == "Museum, gallery") {
            image = new google.maps.MarkerImage('images/Museum.png', size, origin, anchor);
        }
        else if (this.category_title == "National Trust") {
            image = new google.maps.MarkerImage('images/National.png', size, origin, anchor);
        }
        else if (this.category_title == "Nature Reserve") {
            image = new google.maps.MarkerImage('images/red.png', size, origin, anchor);
        }
        else if (this.category_title == "Primary") {
		var size = new google.maps.Size(32, 32);
        var origin = new google.maps.Point(0, 0);
        var anchor = new google.maps.Point(9, 32);
            image = new google.maps.MarkerImage('images/primary.png', size, origin, anchor);
        }
        else {
            image = new google.maps.MarkerImage('images/red.png', size, origin, anchor);
        }
        
        var shadow = new google.maps.MarkerImage('images/s_shadow.png', new google.maps.Size(30, 16), new google.maps.Point(0, 0), new google.maps.Point(4, 15));
        
        var shape = {
            coord: [12, 1, 11, 13, 4, 18, 22, 24, 20, 15, 26, 4],
            type: 'poly'
        };
        
        for (var i = 0; i < category_data.length; i++) {
            var myLatLng = new google.maps.LatLng(this.category_data[i].lat, this.category_data[i].lng);
            var marker = new google.maps.Marker({
                position: myLatLng,
                map: _map,
                shadow: shadow,
                icon: image,
                shape: shape,
                title: this.category_data[i].name
            });
            this.markersArray.push(marker);
            attachInfoBox(marker, this.category_data[i]);
            
            //var ib = new InfoBox(myOptions);		
            //ib.open(theMap, marker);
        
            //var infoBox = new InfoBox(this.category_data[i]);
            // this is standard infobubble but WI fancybox style not possible 
            // attachInfoBubble(marker, this.category_data[i]);
            // attachInfoBox(marker, this.category_data[i]);
        
            //google.maps.event.trigger(marker, "click");
        }
    }
}

function attachInfoBox(marker, pp){
    // var infoBox = new InfoBox(pinpoint_data);
    var InfoBoxContent = document.createElement("div");
    // InfoBoxContent.setAttribute("id", "fancyPopup_contents");
    //  InfoBoxContent.style.cssText = "border: 1px solid black; margin-top: 8px; background: url('./images/info_bg.png'); background-repeat: repeat-x; padding: 5px;";
    InfoBoxContent.style.cssText = "min-height:123px; margin-top: 8px; background: url('./images/bookingInfo_bg.png'); padding: 5px;";
    //InfoBoxContent.style.cssText = "min-height:123px; margin-top: 8px; background: url('./images/info_bg.png') repeat-x; padding: 5px;";
    //  InfoBoxContent.style.cssText = "border: 1px solid black; margin-top: 8px; background: yellow; padding: 5px;";
    
    //   InfoBoxContent.innerHTML = '<div class="popup_inner">' + 
    //   <a target="_blank" href="http://www.abereistedd.co.uk"><img width="116" height="75" border="0" style="float: left; padding-right: 10px;" alt="" src="http://www.stayinginwales.com/trade/accom/photos/204_mainpic.jpg"></a><h3>Abereistedd Hotel</h3><p>West Parade<br>Criccieth LL52 0EN</p><strong>Email:</strong> <a href="mailto:info@abereistedd.co.uk?subject=Enquiry via Wales.info">info@abereistedd.co.uk</a><br><strong>Tel:</strong> 01766 522710<br><a target="_blank" href="http://www.abereistedd.co.uk" id="fancyPopup_btn_more"><img src="/images/bookingInfo_btn_more.png"></a></div>
    
    var popup_inner = document.createElement("div");
    popup_inner.setAttribute("id", "popup_inner");
    InfoBoxContent.appendChild(popup_inner);
    
    var popup_img = document.createElement("div");
    popup_img.setAttribute("id", "popup_img_div");
    var image = document.createElement("img");
    image.setAttribute("id", "popup_img");
    var link = document.createElement("a");
    link.setAttribute("target", "_blank");
    if (pp.url != null) 
        link.setAttribute("href", pp.url);
    else 
        link.setAttribute("href", "#");
    link.appendChild(image);
    popup_img.appendChild(link);
    popup_inner.appendChild(popup_img);
    
    if (pp.image_url != null) 
        {
		image.setAttribute("src", pp.image_url);
		image.setAttribute("width", "105");
		image.setAttribute("height", "75");
		}
    else { // street view
    	
    	image.setAttribute("width", "105");
		image.setAttribute("height", "75");
		image.setAttribute("src", "./images/194_mainpic.jpg");
      	
    }
    // boring image
 /*   else {
        image.setAttribute("src", "./images/194_mainpic.jpg");
		image.setAttribute("width", "105");
		image.setAttribute("height", "75");

		}
	*/	
		
    
    
    var popup_content = document.createElement("div");
    popup_content.setAttribute("id", "popup_content");
    popup_inner.appendChild(popup_content);
    
    var popup_btn_pnl = document.createElement("div");
    popup_btn_pnl.setAttribute("id", "popup_btn_pnl");
    popup_inner.appendChild(popup_btn_pnl);
    
    
    var head = document.createElement("h3");
    head.innerHTML = pp.name;
    popup_content.appendChild(head);
    
    var address = document.createElement("p");
    var addressString = "";
    if (pp.street != null) {
        if (pp.street != "") addressString = pp.street + '<br>';
    }
    if (pp.city != null) {
        if (pp.city != "") addressString += pp.city + '<br>';
    }
    if (pp.postcode != null) {
        if (pp.postcode != "") addressString += pp.postcode + '<br>';
    }
    if (addressString != "") {
        address.innerHTML = addressString;
        popup_content.appendChild(address);
    }
    
    
    if (pp.email != null) {
        if (pp.email != "") {
            var email = document.createElement("a");
            email.setAttribute("href", "mailto:" + pp.email + "?subject=Enquiry via Wales.info");
            email.innerHTML = pp.email;
            popup_content.appendChild(document.createTextNode("Email: "));
            popup_content.appendChild(email);
        }
    }
    
    if (pp.phone != null) {
        if (pp.phone != "") {
            var phone = document.createElement("p");
            phone.innerHTML = "Phone: " + pp.phone;
            popup_content.appendChild(phone);
        }
    }
    
    var itinerary = document.createElement("li");
    itinerary.setAttribute("class", "popup_btn");
    itinerary.setAttribute("id", "itinerary_btn");
    /*itinerary.innerHTML = "Add to Itinerary";*/
    itinerary.setAttribute("onclick", "addtoItinerary(" + pp.siteID + ",\"" + pp.name + "\")");
    itinerary.setAttribute("onmouseover","toggleItineraryBtnColor()");
    itinerary.setAttribute("onmouseout","toggleItineraryBtnColor()");
    popup_btn_pnl.appendChild(itinerary);
    
   
    if (pp.url != null) {
        var link = document.createElement("a");
     
		var web = document.createElement("li");
		web.setAttribute("id", "web_li");
        link.setAttribute("class", "popup_btn");
        link.setAttribute("id", "web_btn");
           link.setAttribute("target", "_blank");
        link.setAttribute("href", pp.url);
		  link.setAttribute("title", pp.url);
          link.setAttribute("onclick","_gaq.push(['_trackEvent', 'More Info', _pp.name]);");
        /*link.innerHTML = "More Info";*/
		str = pp.url;
		/* web.setAttribute("onclick", urlload(str));*/
        web.appendChild(link);
        popup_btn_pnl.appendChild(web);
		
    }
    
    google.maps.event.addListener(marker, "mouseover", function(e){
        _infoBox.setContent(InfoBoxContent);
        _infoBox.open(_map, marker);
         //streetViewImg(marker.getPosition().lat(), marker.getPosition().lng());
    });
}

function streetViewImg(lat, lng){
    var httpReq = null;
    if (window.XMLHttpRequest) {// code for IE7, Firefox, Mozilla, etc.
        httpReq = new XMLHttpRequest();
       /*
        try {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
        } 
        catch (e) {
        }
        */
    }
    else if (window.ActiveXObject) {// code for IE5, IE6
        httpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    var url = "http://cbk0.google.com/cbk?output=thumbnail&w=105&h=75&ll="+ lat+ ","+ lng;
    httpReq.open("GET", url, true);
    httpReq.send(null);
    httpReq.onreadystatechange = function(){
        if (httpReq.readyState == 4) {
            if (httpReq.status == 200) {
            	//image.setAttribute("src", url);
            	document["popup_img"].src = url;
            }
            
        }
    }
}

function urlload(url)
{

window.open(url, "_blank"); 
}

var _ItineraryBtnColor = true;
function toggleItineraryBtnColor(){
     if(_ItineraryBtnColor){
        /*document.getElementById('zongpop').style.backgroundColor="red";*/
		var newImage1 = "url(images/btnItinOver_phone.png)";
		document.getElementById('zongpop').style.background=newImage1;
    }
	else{
	var newImage2 = "url(images/btnItinNorm_phone.png)";
        document.getElementById('zongpop').style.background=newImage2;
    _ItineraryBtnColor = !_ItineraryBtnColor;
        }
}

function addtoItinerary(siteID, name){
        document.getElementById('zongpop').style.backgroundColor="red";
    _itineraryArray[siteID] = name;
    _gaq.push(['_trackEvent', 'MyItinerary', _pp.name, name]);
    //document.getElementById('zongpop').style.backgroundColor = "DAE0F0";
}


function createItinerary(){
    if (document.where.country[3].selected) {
        alert("You need to choose your country");
    }
    else {
    
        var check_it_array = [];
        if (document.itf.it_group.length != undefined) {
            // more than 1 element
            for (i = 0; i < document.itf.it_group.length; i++) {
                if (document.itf.it_group[i].checked == true) check_it_array.push(document.itf.it_group[i].value);
            }
        }
        else {
            if (document.itf.it_group.checked == true) check_it_array.push(document.itf.it_group.value);
        }
        $.fancybox.showActivity();
        var requestObject = {
            q: "services/resteasy",
            output: "json",
            method: "itinerary.create",
            poi: JSON.stringify(check_it_array)
        };
        Drequest(requestObject, function(response){
            if (response['#error']) {
                alert(response['#data']);
                _gaq.push(['_trackEvent', 'ItineraryError', response['#data']]);
            }
            else {
                var itID = response['#data'].itID;
                getZongURI(itID);
                _gaq.push(['_trackEvent', 'ShowZong', _pp.name]);
            }
        });
    }
}

function showItineray(){
    var itineraryFrame = document.getElementById("itineraryFrame");
    itineraryFrame.style.display="block";
    var zongFrameDiv = document.getElementById("zongFrame");
    zongFrameDiv.style.display="none";
    // if the zong frame was previoulsy open then the src will still be set  
    document.getElementById("widget-zong").src ="";
    //document.getElementById("helplink").innerHTML = location.href+"/info.aspx;";
    document.getElementById("itinerary_wrapper").innerHTML = "";
    var itinerary_wrapper = document.createElement('form');
    itinerary_wrapper.name = "itf";
    for (var i in _itineraryArray) {
        var it = document.createElement('input');
        it.type = "checkbox";
        it.name = 'it_group';
        it.value = i;
        it.checked = true;
        
        var label = document.createElement('label');
        label.innerHTML = _itineraryArray[i]+'<br>';
        
        itinerary_wrapper.appendChild(it);
        itinerary_wrapper.appendChild(label);
    }
    document.getElementById("itinerary_wrapper").appendChild(itinerary_wrapper);
    /*
    if (document.getElementById("zong_next_btn") == null) {
        create = document.createElement('input');
        create.setAttribute('type', 'image');
		create.setAttribute('src', 'http://yourpinpoints.com/app/WI/images/GreenNext.png');
        create.setAttribute('id', 'zong_next_btn');
       
        create.setAttribute("onclick", "createItinerary()");
        itineraryFrame.appendChild(create);
    }*/
    _gaq.push(['_trackEvent', 'ShowItinerary', _pp.name]);
}

function getZongURI(itID){

    for (i = 0; i < document.where.country.length; i++) {
        if (document.where.country[i].selected) co = document.where.country[i].value;
    }
    var requestObject = {
        q: "services/resteasy",
        output: "json",
        method: "zong_price.get",
        country_code: co,
        entry_point: "0.25"
    };
    Drequest(requestObject, function(response){
        if (response['#error']) {
            alert(response['#data']);
        }
        else {
            var uri = response['#data'].uri;
            Zong(uri, itID);
        }
    });
    
}
function Zong(uri, itID){

var requestObject = {
        transactionRef: "IT_WI_" + itID,
        itemDesc: "Wales Itinerary",
        redirect: escape("http://yourpinpoints.com/thanks.html"),
        redirectParent: false,
        app: "Wales_Info",
        lang: "en",
        basketUrl: escape(window.location),
        userId: "WI"
    };
    
    var zongFrame = document.getElementById("widget-zong");
    
    zongFrame.src = uri + objectToQueryString(requestObject, true);
    
    
    
    //$.fancybox.hideActivity();
    var itineraryFrame = document.getElementById("itineraryFrame");
    itineraryFrame.style.display = "none";
    var zongFrameDiv = document.getElementById("zongFrame");
    zongFrameDiv.style.display = "block";
   //zongFrame.setAttribute('onload','ZongShowFrame()');
    zongFrame.setAttribute('onload','$.fancybox.hideActivity()');
}

function ZongShowFrame(){
    // this line to ensure the zong fram isn't shown on close and reopen of fancypopup
    document.getElementById("widget-zong").setAttribute('onload','');
    
    $.fancybox.hideActivity();
   
    var itineraryFrame = document.getElementById("itineraryFrame");
    itineraryFrame.style.display = "none";
    var zongFrameDiv = document.getElementById("zongFrame");
    zongFrameDiv.style.display = "block";
    
}

// not used
function ZongHideFrame(){
    var itineraryFrame = document.getElementById("itineraryFrame");
    itineraryFrame.style.display = "block";
    var zongFrameDiv = document.getElementById("zongFrame");
    zongFrameDiv.style.display = "none";
    
}

var DRUPAL_JSON_URL = "http://yourpinpoints.com/";
function Drequest(dataObject, callback){

    var httpReq = null;
    if (window.XMLHttpRequest) {// code for IE7, Firefox, Mozilla, etc.
        httpReq = new XMLHttpRequest();
       /*
        try {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
        } 
        catch (e) {
        }
        */
    }
    else if (window.ActiveXObject) {// code for IE5, IE6
        httpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    var url = DRUPAL_JSON_URL;
    var params = objectToQueryString(dataObject);
    httpReq.open("GET", url + params, true);
    httpReq.send(null);
    httpReq.onreadystatechange = function(){
        if (httpReq.readyState == 4) {
            if (httpReq.status == 200) {
                var response = httpReq.responseText;
                var json = eval('(' + response + ')');
                callback(json);
            }
            else {
                alert("Error - Server May be Down");
            }
        }
    }
}

function objectToQueryString(obj, append){
    append = typeof(append) != 'undefined' ? append : false;
    if (append) 
        var queryStr = "&";
    else 
        var queryStr = "?";
    
    for (var i in obj) {
        var str = i + "=" + obj[i];
        queryStr += str + "&"
    }
    return queryStr.substring(0, queryStr.length - 1)
}

/*
 * unused functions
 *
 */
function ItineraryControl(controlDiv, _map){

    // Set CSS styles for the DIV containing the control
    // Setting padding to 5 px will offset the control
    // from the edge of the map
    controlDiv.style.padding = '5px';
    
    // Set CSS for the control border
    var controlUI = document.createElement('DIV');
    controlUI.style.backgroundColor = 'white';
    controlUI.style.borderStyle = 'solid';
    /*controlUI.style.borderWidth = '2px';*/
    controlUI.style.cursor = 'pointer';
    controlUI.style.textAlign = 'center';
    controlUI.title = 'Click to set the map to Home';
    controlDiv.appendChild(controlUI);
    //<a id="zongpop" href="http://google.ca">Iframe</a>
    // Set CSS for the control interior
    var controlText = document.createElement('a');
    controlText.setAttribute("id", "zongpop");
    controlText.setAttribute("href", "http://google.ie");
        /*controlText.innerHTML = 'Itinerary';*/
    controlUI.appendChild(controlText);
    
    // Setup the click event listeners: simply set the map to
    // Chicago
    google.maps.event.addDomListener(controlUI, 'click', function(){
        //map.setCenter(chicago)
    });
}

