var base_email_url = "/virtualownership/post.php";



function initialize() {
    var mashup = new LessRainMashup();
    mashup.init();
}


LessRainMashup = function() {};

LessRainMashup.prototype.init = function() {

    scope = this;

    scope.params = parameters();

    var controlHTML = [
    '<div id="streetView"></div>',
    '<xiframe class="controlPosition" id="shim" src="" frameborder="0">&nbsp;</xiframe>',
    '<div class="controlPosition" id="controls"></div>',
    '<div id="backButtonContainer"></div>',
    '<div id="nextButtonContainer"></div>',
    '<div id="resetButtonContainer"></div>',

    '<div id="helpButton"></div>',
    '<div id="systemButton"></div>',

    '<a id="alfaurlbottomright" href="http://www.alfagiulietta.com/" target="_new"></a>',

    '<div id="showlink"></div>',
    '<div id="shareFriend"></div>',
    '<a id="shareFacebook" target="_new"></a>',
    '<a id="shareTwitter" target="_new"></a>',
    '<a id="gotosite" href="http://www.alfagiulietta.com/" target="_new"></a>',

    '<div id="helpLayer">',
    '<a id="bExplorer" href="http://www.microsoft.com/Windows/internet-explorer/" target="new"></a>',
    '<a id="bFirefox" href="http://www.getfirefox.com" target="new"></a>',
    '<a id="bSafari" href=" http://www.apple.com/safari/download/" target="new"></a>',
    '<a id="bChrome" href="http://www.google.com/chrome" target="new"></a>',
    '</div>',
    '<div id="alertLayer"><input type="text" /><div id="alertLayerX"></div></div>',
    '<div id="shareFriendLayer"><input type="text" id="form_from"/><input type="text" id="form_to"/><input type="text" id="form_subject" value="Check out the new Giulietta in my driveway"/><textarea type="text" id="form_message"></textarea><div id="form_close"></div><div id="form_send"></div></div>',

    '<div id="noFindLayer">',
    '<input id="addressNoFind" type="text" value="" STYLE="color: #333333; font-family: Georgia; font-style: italic; font-size: 14px;" /><div class="button" id="addressLookupNoFind"></div>',
    '<select id="theerrordropbox"></select>',
    '<div id="theerrordropboxgo"></div>',
    '</div>',

    '<select id="thedropbox"></select>',
    '<div    id="thedropboxgo"></div>',

    '<div id="carBig"></div>',
    '<div id="carMedium"></div>',
    '<div id="carSmall"></div>',

    '<div id="carColour1"></div>',
    '<div id="carColour2"></div>',
    '<div id="carColour3"></div>',
    '<div id="carColour4"></div>',
    '<div id="carColour5"></div>',
    '<div id="carColour6"></div>',
    '<div id="carColour7"></div>',
    '<div id="carColour8"></div>',
    '<div id="carColour9"></div>',

    '<div id="carView"></div>'

    ].join("");

    $("#container").html(controlHTML);


    $("#addressLookupNoFind").bind("click",
    function(e) {
        scope.goStep2();
        scope.goAddressSearch();
    });

    // fire on enter key press too.
    $('#addressNoFind').keyup(function(e) {
        if (e.keyCode == 13) {
            scope.goStep2();
            scope.goAddressSearch();
        }
    });



    $("#thedropboxgo").click(function() {
        scope.handleDropChange("#thedropbox")
    });
    $("#theerrordropboxgo").click(function() {
        scope.handleDropChange("#theerrordropbox")
    });


    $("#thedropbox").html([
    '<option value="none">Please Choose</option>',
    '<option value="01">Champs-&Eacute;lys&eacute;es</option>',
    '<option value="02">Times Square</option>',
    '<option value="03">Las Vegas Boulevard</option>',
    '<option value="04">St-Tropez Marina</option>',
    ].join(""));

    $("#theerrordropbox").html($("#thedropbox").html())

    $("#form_close").click(function() {
        scope.shareFriendHide()
    });
    $("#form_send").click(function() {
        scope.sendTheForm();
    });


    $("#nextButtonContainer").click(function() {
        scope.goNext();
    });
    $("#backButtonContainer").click(function() {
        scope.goPrev();
    })

    $("#showlink").click(function() {
        scope.copyLink();
    })
    $("#shareFriend").click(function() {
        scope.shareFriend();
    })

    $("#resetButtonContainer").click(function() {
        scope.goStep1();
    })
    $("#helpButton").click(function() {
        scope.showHelpLayer()
    });
    $("#systemButton").click(function() {
        scope.showHelpLayer()
    });

    $("#helpLayer").click(function() {
        scope.hideHelpLayer()
    });
    $("#alertLayerX").click(function() {
        scope.hideAlertLayer()
    });


    $("#carBig").click(function() {
        scope.goCarBig()
    });
    $("#carMedium").click(function() {
        scope.goCarMedium()
    });
    $("#carSmall").click(function() {
        scope.goCarSmall()
    });

    $("#carColour1").click(function() {
        thisMovie("carView").setColour1();
    });
    $("#carColour2").click(function() {
        thisMovie("carView").setColour2();
    });
    $("#carColour3").click(function() {
        thisMovie("carView").setColour3();
    });
    $("#carColour4").click(function() {
        thisMovie("carView").setColour4();
    });
    $("#carColour5").click(function() {
        thisMovie("carView").setColour5();
    });
    $("#carColour6").click(function() {
        thisMovie("carView").setColour6();
    });
    $("#carColour7").click(function() {
        thisMovie("carView").setColour7();
    });
    $("#carColour8").click(function() {
        thisMovie("carView").setColour8();
    });
    $("#carColour9").click(function() {
        thisMovie("carView").setColour9();
    });


    if (scope.params.yaw != null
    && scope.params.zoom != null
    && scope.params.pitch != null
    && scope.params.lat != null
    && scope.params.lng != null) {
        scope.showStreetViewFromParams(scope.params.yaw, scope.params.pitch, scope.params.zoom, scope.params.lat, scope.params.lng);
        this.goStep4();
        this.goStepView();
        scope.dropCar(scope.params.carData);
        this.pollFixSocial();
    } else {
        scope.showAddressControls();
    }
}
LessRainMashup.prototype.pollFixSocial = function() {
    var longURL = scope.getMeTheLongURL();Â
    if (longURL.indexOf("yaw=undefined&pitch=undefined&zoom=undefined") == -1) {
        ÂÂ
        var shortener = new URLShortener();
        ÂÂshortener.shorten(longURL, scope.handleSocialLinks);
    } else {
        window.setTimeout(function() {
            scope.pollFixSocial()
        },
        500);
    }
}

LessRainMashup.prototype.handleDropChange = function(elemID) {

    var val = $(elemID).val();
    if (val == "01") {
        scope.goSaved01();
        scope.goStep2();
    } else if (val == "02") {
        scope.goSaved02();
        scope.goStep2();
    } else if (val == "03") {
        scope.goSaved03();
        scope.goStep2();
    } else if (val == "04") {
        scope.goSaved04();
        scope.goStep2();
    }
}

LessRainMashup.prototype.goSaved01 = function() {
    scope.showStreetViewFromParams(254.44, 5.77, 0, 48.873535, 2.295849);
}
LessRainMashup.prototype.goSaved02 = function() {
    scope.showStreetViewFromParams(124.43, -2.9, 0, 40.759259, -73.984753);
}
LessRainMashup.prototype.goSaved03 = function() {
    scope.showStreetViewFromParams(206.16, 5.31, 0, 36.101122, -115.172813);
}
LessRainMashup.prototype.goSaved04 = function() {
    scope.showStreetViewFromParams(202.98, 6.47, 0, 43.271862, 6.638939);
}

LessRainMashup.prototype.resetCarSizeButtons = function() {
    $("#carBig").css("background", "none");
    $("#carMedium").css("background", "none");
    $("#carSmall").css("background", "none");
}

LessRainMashup.prototype.goCarBig = function() {
    this.resetCarSizeButtons();
    $("#carBig").css("background", "url(library/img/size-active.png) no-repeat 4px 2px");
    try {
        thisMovie("carView").setCarSizeBig();
    } catch(e) {
        // might not have loaded yet.
        }
}


LessRainMashup.prototype.goCarMedium = function() {
    this.resetCarSizeButtons();
    $("#carMedium").css("background", "url(library/img/size-active.png) no-repeat 4px 2px");
    thisMovie("carView").setCarSizeMedium();
}
LessRainMashup.prototype.goCarSmall = function() {
    this.resetCarSizeButtons();
    $("#carSmall").css("background", "url(library/img/size-active.png) no-repeat 4px 2px");
    thisMovie("carView").setCarSizeSmall();
}

LessRainMashup.prototype.goRotateUp = function() {
    thisMovie("carView").rotateCarUp();
}
LessRainMashup.prototype.goRotateDown = function() {
    thisMovie("carView").rotateCarDown();
}
LessRainMashup.prototype.goRotateLeft = function() {
    thisMovie("carView").rotateCarLeft();
}
LessRainMashup.prototype.goRotateRight = function() {
    thisMovie("carView").rotateCarRight();
}

LessRainMashup.prototype.showHelpLayer = function() {
    $("#helpLayer").css("display", "block");
}

LessRainMashup.prototype.hideHelpLayer = function() {
    $("#helpLayer").css("display", "none");
}

LessRainMashup.prototype.hideAlertLayer = function() {
    $("#alertLayer").css("display", "none");
}


LessRainMashup.prototype.showAddressControls = function() {
    this.mode = "step1";

    var addressHTML = ['<input id="address" type="text" value="Enter address here" STYLE="color: #333333; font-family: Georgia; font-style: italic; font-size: 14px;" />',
    '<div class="button" id="addressLookup"></div>',
    ].join("");


    $("#controls").html(addressHTML);
    $("#addressLookup").bind("click",
    function(e) {
        scope.goStep2();
        scope.goAddressSearch();
    });


    // fire on enter key press too.
    $('#address').keyup(function(e) {
        if (e.keyCode == 13) {
            scope.goStep2();
            scope.goAddressSearch();
        }
    });


    $('#address').focus(function() {
        if ($('#address').val() == "Enter address here") {
            $('#address').val("");
        }
        $('#address').css("color", "#000");
    })


}

LessRainMashup.prototype.goNext = function() {
    if (this.mode == "step1") {
        this.goStep2();
    } else if (this.mode == "step2") {
        this.goStep3();
    } else if (this.mode == "step3") {
        this.goStep4();
    }
}

LessRainMashup.prototype.goPrev = function() {
    if (this.mode == "step2") {
        this.goStep1();
    } else if (this.mode == "step3") {
        this.goStep2();
    } else if (this.mode == "step4") {
        this.goStep3();
    }
}


LessRainMashup.prototype.goStep1 = function() {
    this.mode = "step1";
    $("#streetView").css("display", "none");
    $("#container").css("background", "url(library/img/bg-01.png)");

    $("#thedropbox").hide();
    $("#thedropboxgo").hide();

    $("#noFindLayer").hide();

    $("#alfaurlbottomright").hide();

    $("#controls").css("top", "191px");
    $("#controls").css("left", "78px");

    $("#nextButtonContainer").css("display", "none");
    $("#backButtonContainer").css("display", "none");
    $("#resetButtonContainer").css("display", "none");

    this.hideCar();
}

LessRainMashup.prototype.goStep2 = function() {
    this.mode = "step2";
    $("#streetView").css("display", "block");
    $("#container").css("background", "url(library/img/bg-02.png)");

    this.putControlTopRight();

    $("#thedropbox").show();
    $("#thedropboxgo").show();

    $("#alfaurlbottomright").show();

    $("#noFindLayer").hide();

    $("#nextButtonContainer").css("background", "url(library/img/button-confirm.png)");
    $("#nextButtonContainer").css("top", "513px");
    $("#nextButtonContainer").css("left", "340px");
    $("#nextButtonContainer").css("display", "block");

    $("#resetButtonContainer").css("display", "none");
    $("#backButtonContainer").css("display", "none");

    this.hideCarSizeControls();
    this.hideCarRotationControls();
    this.hideCarColourControls();
    this.hideCar();
}

LessRainMashup.prototype.goStep3 = function() {

    this.oldMode = this.mode;

    this.mode = "step3";
    $("#container").css("background", "url(library/img/bg-03.png)");
    $("#backButtonContainer").css("display", "block");


    $("#nextButtonContainer").css("background", "url(library/img/button-finish.png)");
    $("#nextButtonContainer").css("top", "513px");
    $("#nextButtonContainer").css("left", "640px");
    $("#nextButtonContainer").css("display", "block");

    $("#noFindLayer").hide();

    this.showCarSizeControls();
    this.showCarRotationControls();
    this.showCarColourControls();

    $("#showlink").css("display", "none");
    $("#shareFriend").css("display", "none");
    $("#shareFacebook").css("display", "none");
    $("#shareTwitter").css("display", "none");
    $("#gotosite").css("display", "none");

    if (this.oldMode == "step4") {
        $("#carView").show();
    } else {
        this.dropCar();
    }

}

LessRainMashup.prototype.goStep4 = function() {
    this.mode = "step4";
    $("#container").css("background", "url(library/img/bg-04.png)");
    $("#nextButtonContainer").css("display", "none");
    $("#backButtonContainer").css("display", "block");

    $("#showlink").css("display", "block");
    $("#shareFriend").css("display", "block");
    $("#shareFacebook").css("display", "block");
    $("#shareTwitter").css("display", "block");
    $("#gotosite").css("display", "block");

    this.hideCarSizeControls();
    this.hideCarRotationControls();
    this.hideCarColourControls();

    this.storeCarData();

    this.setUpSocialLinks();

}

LessRainMashup.prototype.setUpSocialLinks = function() {
    var longURL = scope.getMeTheLongURL();
    var shortener = new URLShortener();
    shortener.shorten(longURL, scope.handleSocialLinks);
    //scope.handleSocialLinks(longURL)
}

LessRainMashup.prototype.handleSocialLinks = function(shortURL) {
    $("#shareFacebook").get(0).setAttribute("href", "http://facebook.com/sharer.php?u=" + shortURL);
    $("#shareTwitter").get(0).setAttribute("href", "http://twitter.com/home?status=Check out this Alfa Giulietta sitting in my Driveway! " + shortURL);
}




LessRainMashup.prototype.sendTheForm = function() {


    // validate first.
    var error = false;

    if ($("#form_from").val() == "" || $("#form_from").val().indexOf("@") == -1 || $("#form_from").val().indexOf(".") == -1) {
        error = true;
        $("#form_from").css("background", "pink");
    } else {
        $("#form_from").css("background", "#f3eff0");
    }

    if ($("#form_to").val() == "" || $("#form_to").val().indexOf("@") == -1 || $("#form_to").val().indexOf(".") == -1) {
        error = true;
        $("#form_to").css("background", "pink");
    } else {
        $("#form_to").css("background", "#f3eff0");
    }

    if ($("#form_subject").val() == "") {
        error = true;
        $("#form_subject").css("background", "pink");
    } else {
        $("#form_subject").css("background", "#f3eff0");
    }

    if ($("#form_message").val() == "") {
        error = true;
        $("#form_message").css("background", "pink");
    } else {
        $("#form_message").css("background", "#f3eff0");
    }

    //------------
    if (error) {
        return;
    } else {
        scope.doTheSend();
        scope.shareFriendHide();
    }

}

LessRainMashup.prototype.doTheSend = function() {

    $.ajax({
        type: 'POST',
        url: base_email_url,
        data: {
            "to": $("#form_to").val(),
            "from": $("#form_from").val(),
            "subject": $("#form_subject").val(),
            "message": $("#form_message").val()
        }
    });

}


LessRainMashup.prototype.shareFriend = function() {
    $("#shareFriendLayer").show();

    $("#carView").css("top", "-800px");
    $("#streetView").css("top", "-800px");

    var longURL = scope.getMeTheLongURL();
    var shortener = new URLShortener();
    shortener.shorten(longURL, scope.handleShareFriendResponse);
}

LessRainMashup.prototype.shareFriendHide = function() {
    $("#shareFriendLayer").hide();
    $("#carView").css("top", "111px");
    $("#streetView").css("top", "111px");
}


LessRainMashup.prototype.handleShareFriendResponse = function(surl) {
    $("#form_message").val("Check out the new Alfa Romeo Giulietta sitting in my driveway:\n\n" + surl);
}


LessRainMashup.prototype.storeCarData = function() {
    // store data.... we'll get reverted to current car state if the car is refreshed etc.
    try {
        thisMovie("carView").storeCarData();
    } catch(e) {}
}

LessRainMashup.prototype.goStepError = function() {

    this.mode = "error";

    scope.showAddressControls();

    $("#container").css("background", "url(library/img/bg-02.png)");

    $("#nextButtonContainer").css("display", "none");
    $("#backButtonContainer").css("display", "none");

    $("#noFindLayer").show();

}


LessRainMashup.prototype.goStepView = function() {
    scope.showAddressControls();
    $("#resetButtonContainer").css("display", "block");
    $("#nextButtonContainer").css("display", "none");
    $("#backButtonContainer").css("display", "none");
    this.putControlTopRight();
}

LessRainMashup.prototype.putControlTopRight = function() {
    $("#controls").css("top", "32px");
    $("#controls").css("left", "448px");
}

LessRainMashup.prototype.showCarSizeControls = function() {
    $("#carBig").css("display", "block");
    $("#carMedium").css("display", "block");
    $("#carSmall").css("display", "block");
}

LessRainMashup.prototype.hideCarSizeControls = function() {
    $("#carBig").css("display", "none");
    $("#carMedium").css("display", "none");
    $("#carSmall").css("display", "none");
}

LessRainMashup.prototype.showCarRotationControls = function() {
    $("#carRotateUp").css("display", "block");
    $("#carRotateDown").css("display", "block");
    $("#carRotateLeft").css("display", "block");
    $("#carRotateRight").css("display", "block");
}

LessRainMashup.prototype.hideCarRotationControls = function() {
    $("#carRotateUp").css("display", "none");
    $("#carRotateDown").css("display", "none");
    $("#carRotateLeft").css("display", "none");
    $("#carRotateRight").css("display", "none");
}

LessRainMashup.prototype.showCarColourControls = function() {
    $("#carColour1").css("display", "block");
    $("#carColour2").css("display", "block");
    $("#carColour3").css("display", "block");
    $("#carColour4").css("display", "block");
    $("#carColour5").css("display", "block");
    $("#carColour6").css("display", "block");
    $("#carColour7").css("display", "block");
    $("#carColour8").css("display", "block");
    $("#carColour9").css("display", "block");
}

LessRainMashup.prototype.hideCarColourControls = function() {
    $("#carColour1").css("display", "none");
    $("#carColour2").css("display", "none");
    $("#carColour3").css("display", "none");
    $("#carColour4").css("display", "none");
    $("#carColour5").css("display", "none");
    $("#carColour6").css("display", "none");
    $("#carColour7").css("display", "none");
    $("#carColour8").css("display", "none");
    $("#carColour9").css("display", "none");
}


LessRainMashup.prototype.goAddressSearch = function() {


    var geocoder = new GClientGeocoder();
    var address = $("#address").val();

    if ($("#addressNoFind").val() != "") {
        address = $("#addressNoFind").val()
        $("#address").val(address);
        $("#addressNoFind").val("");
    }

    geocoder.getLatLng(
    address,
    function(point) {
        if (!point) {
            scope.goStepError();
        } else {
            scope.showStreetViewFromAddress(new GLatLng(point.lat(), point.lng()));

        }
    }
    );
}


LessRainMashup.prototype.showStreetViewFromParams = function(ayaw, apitch, zoom, lat, lng) {

    scope.goStep2();

    scope.streetClient = new GStreetviewClient();

    var myLoc = new GLatLng(lat, lng);
    var myPOV = {
        yaw: Number(ayaw),
        pitch: Number(apitch)
    };
    var myFeatures = {
        userPhotos: false
    }

    var viewOptions = {
        latlng: myLoc,
        pov: myPOV,
        enableFullScreen: false,
        features: myFeatures
    };

    scope.streetView = new GStreetviewPanorama($("#streetView").get(0), viewOptions);


    GEvent.addListener(scope.streetView, "initialized",
    function(aLocation) {
        scope.lat = aLocation.lat;
        scope.lng = aLocation.lng;
    });


}

LessRainMashup.prototype.showStreetViewFromAddress = function(point) {
    scope.streetClient = new GStreetviewClient();
    scope.streetClient.getNearestPanorama(point, scope.lookupResponse);

}

LessRainMashup.prototype.lookupResponse = function(response) {
    if (response.code != 200) {
        scope.goStepError();
    } else if (response.code == 200) {

        var myLoc = new GLatLng(response.Location.lat, response.Location.lng);
        var myPOV = {
            yaw: 100.22,
            pitch: 20.5
        };
        var myFeatures = {
            userPhotos: false
        }
        var viewOptions = {
            latlng: myLoc,
            pov: myPOV,
            enableFullScreen: false,
            features: myFeatures
        };

        scope.streetView = new GStreetviewPanorama($("#streetView").get(0), viewOptions);

        GEvent.addListener(scope.streetView, "initialized",
        function(aLocation) {
            scope.lat = aLocation.lat;
            scope.lng = aLocation.lng;
        });


    }
}



LessRainMashup.prototype.dropCar = function(carData) {

    makeTheFlashGo(carData);

    $("#carView").show();
    this.goCarBig();

}


LessRainMashup.prototype.hideCar = function() {
    $("#carView").hide();

}


LessRainMashup.prototype.getMeTheLongURL = function() {
    var newPOV = scope.streetView.getPOV();
    var yaw = newPOV.yaw;
    var pitch = newPOV.pitch;
    var zoom = newPOV.zoom;

    try {
        var carData = thisMovie("carView").getCurrentCarData();
    } catch(e) {
        var carData = scope.params.carData;
    }

    var longURL = "http://" + document.location.hostname + document.location.pathname + "?yaw=" + yaw + "&pitch=" + pitch + "&zoom=" + zoom + "&lat=" + scope.lat + "&lng=" + scope.lng + "&carData=" + carData;
    return longURL;
}

LessRainMashup.prototype.copyLink = function() {

    var longURL = scope.getMeTheLongURL();
    var shortener = new URLShortener();
    shortener.shorten(longURL, scope.handleBitlyResponse);

}


LessRainMashup.prototype.handleBitlyResponse = function(shortURL) {
    $("#alertLayer").show();
    $("#alertLayer input").val(shortURL);
    //prompt("You can share this link, to return to this driveway view:", shortURL);
}


function parameters()
 {
    var url = unescape(document.location.search)
    var retVal = {},
    parse = url.substr(1, url.length).split("&"),
    i = 0,
    kv_pair;
    if (parse !== null)
    {
        for (; i < parse.length; i++)
        {
            kv_pair = parse[i].split("=");
            retVal[kv_pair[0]] = kv_pair[1];
        };

    };

    return retVal;
}

















/** ******************************* **/



function thisMovie(movieName)
 {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
    } else {
        return document[movieName];
    }
}

function sendToActionScript(value) {
    thisMovie("carView").sendToActionScript(value);
}

function makeTheFlashGo(passedData) {

    var flashvars = {};
    flashvars.deepLink = "";
    flashvars.encoding = "western";
    if (passedData) {
        flashvars.carData = passedData;
    }
    var params = {};
    params.wmode = "transparent";
    params.bgcolor = "#FFFFFF";
    params.allowScriptAccess = "always";
    params.swLiveConnect = "true";
    params.base = "./";
    params.allowFullscreen = "true";

    var attributes = {};
    attributes.id = "carView";
    attributes.name = "carView";

    swfobject.embedSWF("flash/main.swf?v=3", "carView", "710", "300", "10", "flash/expressInstall.swf", flashvars, params, attributes);

    swfobject.embedSWF("flash/main.swf?v=3", "swfContainer", "710", "300", "10", "flash/expressInstall.swf", flashvars, params, attributes);

}










