﻿var geocoder, location1, location2, gDir;
var drivingDistance = null;
var minimumDistance = 5.00;
var minimumCharge = 25.00;
var halfLoad = 30.00;
var fullLoad = 50.00;
var perMile = 1.00;

function initialize() {
    geocoder = new GClientGeocoder();
    gDir = new GDirections();
    GEvent.addListener(gDir, "load", function() {
        var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
        var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
        drivingDistance = drivingDistanceMiles;
        CalcPrice();
        //document.getElementById('results').innerHTML = '<strong>Address 1: </strong>' + location1.address + ' (' + location1.lat + ':' + location1.lon + ')<br /><strong>Address 2: </strong>' + location2.address + ' (' + location2.lat + ':' + location2.lon + ')<br /><strong>Driving Distance: </strong>' + drivingDistanceMiles + ' miles (or ' + drivingDistanceKilometers + ' kilometers)';
    });
}

function showLocation() {
    geocoder.getLocations(document.forms[0].address1.value, function(response) {
        if (!response || response.Status.code != 200) {
            //alert("Sorry, we were unable to geocode the first address");
        }
        else {
            location1 = { lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address };
            geocoder.getLocations(document.forms[0].address2.value, function(response) {
                if (!response || response.Status.code != 200) {
                    //alert("Sorry, we were unable to geocode the second address");
                }
                else {
                    location2 = { lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address };
                    gDir.load('from: ' + location1.address + ' to: ' + location2.address);
                }
            });
        }
    });
}

function CalcPrice() {
    var startCost = 0;
    var diffMiles = drivingDistance - minimumDistance;
    switch ($("input[name='rdLoad']:checked").val()) {
        case "0":
            startCost = minimumCharge;
            break;
        case "1":
            startCost = halfLoad;
            break;
        case "2":
            startCost = fullLoad;
            break;
    }
    if (diffMiles > 0) {
        startCost = startCost + (diffMiles * perMile);
    }
    var cost = "Your message has been sent, the estimated cost is:  £" + parseInt(startCost).toString() + ".00";
    var dataStr = "loadsize=" + $("input[name='rdLoad']:checked").val() + "&address1=" + encodeURIComponent($("#address1").val());
    dataStr += "&address2=" + encodeURIComponent($("#address2").val()) + "&distance=" + drivingDistance + "&name=" + encodeURIComponent($("#txtname").val());
    dataStr += "&tel=" + encodeURIComponent($("#txttel").val()) + "&email=" + encodeURIComponent($("#txtemail").val());
    dataStr += "&message=" + encodeURIComponent($("#txtrequest").val()) + "&cost=" + parseInt(startCost).toString();
    var req = $.ajax({
        type: "POST",
        url: "/Handler1.ashx?op=sendrequest",
        data: dataStr,
        error: function(req, json) {

        },
        success: function(html) {

        $("#EstimatedPrice").html(cost);
        $("#ContentBody").unblock();
            return;
        }
    });
    $('#ContentBody').block('Please wait..', { backgroundImage: "url(Images/loadingAnimation2.gif)", backgroundRepeat: 'no-repeat', backgroundPosition: 'center', backgroundColor: '#202020', opacity: '0.8', width: '980px' });
}
 
function loadCornerz() {
    $('#PageContainer').cornerz({ radius: 10, corners: "tl tr bl br", borderWidth: 0, background: '#191919', fixIE: 'true' });
    $('#TopMenuContainer').cornerz({ radius: 10, corners: "tl tr bl br", borderWidth: 0, background: '#191919', fixIE: 'true' });
    $('div.PageOptions').cornerz({ radius: 10, corners: "tl tr bl br", borderWidth: 0, background: '#191919', fixIE: 'true' });
    $('#PageImageContainer').cornerz({ radius: 10, corners: "tl tr bl br", borderWidth: 0, background: '#191919', fixIE: 'true' });
    $('#ContentBody').cornerz({ radius: 10, corners: "tl tr bl br", borderWidth: 0, background: '#191919', fixIE: 'true' });
}



function adjustContentHeight() {

    /*var h = parseInt($("div.ContentContainer").height()) + 200;
    if (h < 780) {
        h = 780;
    }
    var ht = h + "px";
    var ht2 = (h) + "px";
    $("div.ContentContainer").css({ 'height': ht });
    $("#BodyContainer").css({ 'height': ht2 });*/

    // keep track of the tallest column
    var tallest = 0;

    // loop through columns and find the tallest
    $('div.BodyColumns').each(function() {
        if ($(this).outerHeight(true) > tallest)
            tallest = $(this).outerHeight(true);
    });

    // loop through columns and adjust height as necessary
    $('div.BodyColumns').each(function() {

        // check if current column needs to be adjusted
        if ($(this).outerHeight(true) < tallest) {
            // set new height
            $(this).height(tallest);
            $("#BodyContainer").height(tallest);
        }
    });

}
function fnSaveHeading() {
    if ($('#form1').validationEngine({ returnIsValid: true }) == true) {
        var dataStr = "pid=" + $("#txtpageid").val() + "&h=" + encodeURIComponent($("#txtheading").val()) + "&t=" + encodeURIComponent($("#txttitle").val()) + "&d=" + encodeURIComponent($("#txtdesc").val()) + "&k=" + encodeURIComponent($("#txtkeywords").val());
        var req = $.ajax({
            type: "POST",
            url: "/SiteHandler.ashx?op=saveheading",
            data: dataStr,
            error: function(req, json) {

            //alert(json);
            $("#HeadingResponse").html('Update Not Saved!');
            },
            success: function(html) {

                if (html == "success") {
                    $("#HeadingResponse").html('Update Successful!');
                }
                else {
                    $("#HeadingResponse").html('Update Not Saved!');
                }
                $("div.ContentContainer").unblock();
                return;
            }
        });

        $('div.ContentContainer').block('Please wait..', { backgroundImage: "url(Images/loadingAnimation2.gif)", backgroundRepeat: 'no-repeat', backgroundPosition: 'center', backgroundColor: '#ffffff', opacity: '0.8', width: '640px' });
    }
}
function SavePage() {
    if ($('#form1').validationEngine({ returnIsValid: true }) == true) {

        var sum = "";
        var bod = "";
        var im = "";
        if ($.fck.content('FCKeditor1')) {
            sum = $.fck.content('FCKeditor1');
        }
        if ($.fck.content('FCKeditor2')) {
            bod = $.fck.content('FCKeditor2');
        }
        if ($.fck.content('FCKeditor3')) {
            im = $.fck.content('FCKeditor3');
        }

        var dataStr = "path=" + encodeURIComponent($("#txtpath").val()) + "&pid=" + $("#txtpageid").val() + "&h=" + encodeURIComponent($("#txtheading").val()) + "&s=" + encodeURIComponent(sum) + "&b=" + encodeURIComponent(bod) + "&im=" + encodeURIComponent(im) + "&t=" + encodeURIComponent($("#txttitle").val()) + "&d=" + encodeURIComponent($("#txtdesc").val()) + "&k=" + encodeURIComponent($("#txtkeywords").val());
        var req = $.ajax({
            type: "POST",
            url: "/SiteHandler.ashx?op=savepage",
            data: dataStr,
            error: function(req, json) {

                //alert(json);
                $("#HeadingResponse").html('Update Not Saved!');
            },
            success: function(html) {

                if (html == "success") {
                    $("#HeadingResponse").html('Update Successful!');
                }
                else {
                    $("#HeadingResponse").html('Update Not Saved!');
                }
                $("div.ContentContainer").unblock();
                return;
            }
        });

        $('div.ContentContainer').block('Please wait..', { backgroundImage: "url(Images/loadingAnimation2.gif)", backgroundRepeat: 'no-repeat', backgroundPosition: 'center', backgroundColor: '#ffffff', opacity: '0.8', width: '640px' });
    }
}
function PublishPageNow() {
    if ($('#form1').validationEngine({ returnIsValid: true }) == true) {



        var dataStr = "path=" + encodeURIComponent($("#txtpath").val());
        var req = $.ajax({
            type: "POST",
            url: "/SiteHandler.ashx?op=publishpagenow",
            data: dataStr,
            error: function(req, json) {

                //alert(json);
                $("#HeadingResponse").html('Publish Not Saved!');
            },
            success: function(html) {

                if (html == "success") {
                    $.jqURL.loc($.jqURL.strip());
                }
                else {
                    $("#HeadingResponse").html('Publish Not Saved!');
                }
                $("div.ContentContainer").unblock();
                return;
            }
        });

        $('div.ContentContainer').block('Please wait..', { backgroundImage: "url(Images/loadingAnimation2.gif)", backgroundRepeat: 'no-repeat', backgroundPosition: 'center', backgroundColor: '#ffffff', opacity: '0.8', width: '640px' });
    }
}
function fnLogin() {
    if ($('#form1').validationEngine({ returnIsValid: true }) == true) {
        $("#loginValidation").html('&nbsp;');
        var u = $("#txtusername").val();
        var p = $("#txtpassword").val();

        var dataStr = "u=" + u + "&p=" + p;
        var req = $.ajax({
            type: "POST",
            url: "/SiteHandler.ashx?op=loginvalidation",
            data: dataStr,
            error: function(req, json) {

                alert(json);
            },
            success: function(html) {
                
                if (html == "failure") {
                    $("#loginValidation").html('Please check your details and try again');
                }
                else {
                    $.jqURL.loc(html);
                }
                $("div.ContentContainer").unblock();
                return;
            }
        });

        $('div.ContentContainer').block('Please wait..', { backgroundImage: "url(Images/loadingAnimation2.gif)", backgroundRepeat: 'no-repeat', backgroundPosition: 'center', backgroundColor: '#ffffff', opacity: '0.8', width: '640px' });
    }
}
function fnLogout() {
    var req = $.ajax({
        type: "POST",
        url: "/SiteHandler.ashx?op=logout",
        data: "none",
        error: function(req, json) {

            alert(json);
        },
        success: function(html) {

            
                $.jqURL.loc("/Home.aspx");
            
            $("div.ContentContainer").unblock();
            return;
        }
    });

    $('div.ContentContainer').block('Please wait..', { backgroundImage: "url(Images/loadingAnimation2.gif)", backgroundRepeat: 'no-repeat', backgroundPosition: 'center', backgroundColor: '#ffffff', opacity: '0.8', width: '640px' });
}
function LoadEditPage() {
    var url = $.jqURL.url() + "?edit=true";
    $.jqURL.loc(url);
}


// Floating drop zone image logic
function registerFloater() {
    var slideTime = 700;
    var topMargin = 0;
    winOnResize(); // set initial position
    xAddEventListener(window, 'resize', winOnResize, false);
    xAddEventListener(window, 'scroll', winOnScroll, false);
    return;
}
function winOnResize() {
    var slideTime = 700;
    var topMargin = 0;
    xMoveTo('toolbarmenu', 0, topMargin);
    xShow('toolbarmenu');
    winOnScroll(); // initial slide
}
function winOnScroll() {
    var slideTime = 700;
    var topMargin = 0;
    xSlideTo('toolbarmenu', xLeft('toolbarmenu'), xScrollTop() + topMargin, slideTime);
}

function markCurrentPage() {
    var surl = $.jqURL.strip();
    var url = "/" + surl.replace($("#basehref1").attr('href'), "");
    $("#main_navigation li a").each(function() {
        var href = $(this).attr('href');
        if (url.toLowerCase() == href.toLowerCase()) {
            $(this).addClass('mainnavSelect');
        }
    });
  
}

function loadTwitterJuitter() {
    $.Juitter.start({
        searchType: "fromUser", // needed, you can use "searchWord", "fromUser", "toUser"
        searchObject: "unilabplus", // needed, you can insert a username here or a word to be searched for, if you wish multiple search, separate the words by comma.
        //searchType: "searchWord", // needed, you can use "searchWord", "fromUser", "toUser"
        //searchObject: "mobile", // needed, you can insert a username here or a word to be searched for, if you wish multiple search, separate the words by comma.

        // The values below will overwrite the ones on the Juitter default configuration. 
        // They are optional here.
        // I'm changing here as a example only
        lang: "en", // restricts the search by the given language
        live: "live-90", // the number after "live-" indicates the time in seconds to wait before request the Twitter API for updates.
        placeHolder: "juitterContainer", // Set a place holder DIV which will receive the list of tweets example <div id="juitterContainer"></div>
        loadMSG: "image/gif", // Loading message, if you want to show an image, fill it with "image/gif" and go to the next variable to set which image you want to use on 
        imgName: "Images/loadingAnimation2.gif", // Loading image, to enable it, go to the loadMSG var above and change it to "image/gif"
        total: 10, // number of tweets to be show - max 100
        readMore: "Click to read", // read more message to be show after the tweet content
        nameUser: "image", // insert "image" to show avatar of "text" to show the name of the user that sent the tweet 
        openExternalLinks: "newWindow", // here you can choose how to open link to external websites, "newWindow" or "sameWindow"
        filter: "sex->*BAD word*,porn->*BAD word*,fuck->*BAD word*,shit->*BAD word*"  // insert the words you want to hide from the tweets followed by what you want to show instead example: "sex->censured" or "porn->BLOCKED WORD" you can define as many as you want, if you don't want to replace the word, simply remove it, just add the words you want separated like this "porn,sex,fuck"... Be aware that the tweets will still be showed, only the bad words will be removed
    });


}

function loadYouTubeList() {
    $("ul.ytdemo1").ytplaylist({ addThumbs: false, autoPlay: false, holderId: 'ytvideo', playerWidth:150, playerHeight:120 });
}

function loadRSSItem(id) {

    tb_show("News", "/SiteHandler.ashx?op=getrssitem&height=300&width=500&modal=false&rid=" + id, null);


}

$(document).ready(function() {
    loadCornerz();

    var floater = $("#toolbarmenu").height();

    if (floater != null) {
        var editmode = $.jqURL.get('edit');
        if (editmode == "true") {
            registerFloater();
            $.fck.path = '/fckeditor/';
            $('#FCKeditor1').fck({ toolbar: 'Basic', height: 125, width: 440 });
            $('#FCKeditor2').fck({ toolbar: 'Basic', height: 800, width: 640 });
            $('#FCKeditor3').fck({ toolbar: 'Basic', height: 150, width: 150 });
            $('#ArticleHeadingContainer').css({ 'height': '300px' });
        }
    }

    $('#form1').validationEngine();

    markCurrentPage();
    //loadYouTubeList();
    //loadTwitterJuitter();

    adjustContentHeight();
});
