// Require jQuery 1.3.1+
//
// Author: Joel Nagy
//------------------------------------------------------------------
// Links to play a video should be called: goVplay('GUID-STRING-GOES-HERE')

//var imageDataURL = CONNECTION_TYPE + '1.255.11.193' + IMAGEDATA_URL_PART;
var imageDataURL = CONNECTION_TYPE + WEBSITE_URL + IMAGEDATA_URL_PART;

var ssCloseButton = CONNECTION_TYPE + RESOURCE_SERVER_URL + "/image_25012D89-6099-47AA-AC73-33E8E84E89AA.arox";
var ssPlayButton = CONNECTION_TYPE + RESOURCE_SERVER_URL + "/image_85AD17FF-027C-49BE-80AE-EDC9FCEB7E17.arox";
var ssPauseButton = CONNECTION_TYPE + RESOURCE_SERVER_URL + "/image_1E57F1F2-5C0D-439B-96B5-FCB0F51E6B44.arox";
var ssNextButton = CONNECTION_TYPE + RESOURCE_SERVER_URL + "/image_D5148DD2-785A-48C3-85DE-243E5FC101C4.arox";
var ssPrevButton = CONNECTION_TYPE + RESOURCE_SERVER_URL + "/image_07A1F44D-7E29-43D8-9468-8645E9D3A287.arox";
var ssDoubleArrowDownButton = CONNECTION_TYPE + RESOURCE_SERVER_URL + "/image_E9A15983-E038-4635-8660-C1BD99D09410.arox";
var ssDoubleArrowUpButton = CONNECTION_TYPE + RESOURCE_SERVER_URL + "/image_6B1D7C11-A368-4F00-98B1-6A8DFD753013.arox";
var ssControllerBackground = CONNECTION_TYPE + RESOURCE_SERVER_URL + "/image_8172FEFA-1513-4803-963E-CEA80181E766.arox";
var ssDiggIcon = CONNECTION_TYPE + RESOURCE_SERVER_URL + "/image_5A4844F8-4790-4994-9B48-ECB5D0761CA6.arox";
var ssFacebookIcon = CONNECTION_TYPE + RESOURCE_SERVER_URL + "/image_10284109-B05C-4E28-8E4D-85A928BB9A89.arox";
var ssTwitterIcon = CONNECTION_TYPE + RESOURCE_SERVER_URL + "/image_471cdda5-e1a0-4ef7-ae2d-f61bd1de3229.arox";
var images;

var selectedImageGuid = '';
var slideshowBaseHeight = 425;
var slideshowBaseWidth = 758;
var slideshowCurrentTitle = '';
var slideshowCurrentDescription = '';
var slideshowCurrentImageGuid = '';
var slideshowShareLink = '';
var slideshowShareEmbed = "<img><a href='{0}'><img src='" + CONNECTION_TYPE + RESOURCE_SERVER_URL + "/image_{1}' width='758' height='335' /></a></img>";

// VIDEO GLOBALS
var $videoGuid, $sortCat, $showNextPrev, $baseUrl, $namodelCodeQS = '', $startSlideshow = 'true', $mediaType = 'video', $allowSharing = true, $serviceUri = 'default'; $inlinePlayers = {};
var __winHeight = 0;
var __opacity = 1; // set BG to 1% for browser compliant modal bg, let Flash handle the official design sanctioned opacity level

// BROWSER GLOBALS
var __nav = navigator.userAgent.toLowerCase();
var $ready = false;

$(document).ready(function ()
{
    window.ie6 = $.browser.msie && parseInt($.browser.version) < 7;
    window.ie = $.browser.msie;
    window.gecko = $.browser.mozilla;
    window.macppc = __nav.indexOf('ppc') > 0 && __nav.indexOf('mac') > 0;
});

// Dimensions of the Viewable Window
window.getHeight = function ()
{
    if (window.innerHeight) return window.innerHeight;
    else if (document.documentElement.clientHeight) return document.documentElement.clientHeight;
    else if (document.body.clientHeight) return document.body.clientHeight;
    else return document.body.offsetHeight;
};
window.getWidth = function ()
{
    if (window.innerWidth) return window.innerWidth;
    else if (document.documentElement.clientWidth) return document.documentElement.clientWidth;
    else if (document.body.clientWidth) return document.body.clientWidth;
    else return document.body.offsetWidth;
};

// API: launch video
// sends input to flash; loads player swf using swfload(swfobject)
// Example HTML: <a href="javascript:goVplay('http://cache.bmwusa.com/Swf_00000000-0000-0000-0000-000000000000.arox', 'e0b74591-9a91-47b4-9675-6332482cae76', 'none', false, 'www.bmwusa.com/index.html', 'namodelcode=0920');">THUMBNAILorTEXT</a>

/*	new param nmaes
swfUrl, 
videoGuid,		passed to webservice & added to deeplink param 
sortCat, 		added to deeplink param
showNextPrev, 	
allowSharing, 	
baseUrl, 		the URL from which deeplink is created for sharing, etc.
namodelCodeQS, 	
mediaType		"video", or "image"
serviceUri		if present or not 'default', will use this service url [with same SOAP structure for video] defaults to "/bmwusaservices/videodataservice.asmx?op=VideoDataXml"
*/

function goVplay(swfUrl, videoGuid, sortCat, showNextPrev, allowSharing, baseUrl, namodelCodeQS, mediaType, serviceUri, divId)
{
    //baseUrl = encodeURIComponent(baseUrl);
    if (serviceUri != null)
    {
        serviceUri = encodeURIComponent(serviceUri);
    }


    if (divId != null && $mediaType == 'video')
    {

        goInline(swfUrl, videoGuid, sortCat, showNextPrev, allowSharing, baseUrl, namodelCodeQS, mediaType, serviceUri, divId);
        return;
    }
    // store params
    $videoGuid = videoGuid;
    $sortCat = sortCat;
    $showNextPrev = showNextPrev;
    $baseUrl = (baseUrl.indexOf("http") == -1) ? 'http://' + baseUrl : baseUrl;
    $namodelCodeQS = namodelCodeQS;
    $mediaType = (mediaType == null) ? 'video' : mediaType;
    $serviceUri = (serviceUri != undefined && serviceUri != null) ? serviceUri : 'default';
    $allowSharing = allowSharing;
    // launch modal player...
    pauseAllInlineVideos();
    if (!$ready)
    {
        return;
    }
    //    try {
    // hide Selects for ie6
    if (window.ie6)
        toggleSelects('off');


    // launch/show modal vplayer
    if (_$('vplayswf') == null)
    {
        // Main Container

        var $vplay = $('<div id="vplayContainer" style="display: block; z-index: 999999; top: 0; left: 0; width: 100%; height: 0; position: ' + (window.ie6 ? 'absolute' : 'fixed') + '; overflow: hidden; background: transparent"></div>').prependTo($(document.body));
        // SWF container
        var $vplayInner = $('<div id="vplay" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: transparent"></div>').prependTo($vplay);
        // Close button
        $('<div style="display: block; z-index: 1000000; top: 5px; right: 30px; overflow: hidden; position: absolute; height: 22px; width: 100px"><a href="javascript:noVplay(true)" style="font-family: sans-serif; text-decoration: none; color: black; font-size: 10px; float: right;">[close]</a></div>').prependTo($vplay);
        // Background
        var $vplayBG = $('<div id="vplayBG" style="display: block; z-index: 999990; top: 0; left: 0; width: 100%; height: 0; position: ' + (window.ie6 ? 'absolute' : 'fixed') + '; overflow: hidden; background: white; opacity: 0.01"></div>').prependTo($(document.body));

        var wm = 'transparent';
        if (window.gecko && window.macppc)
            wm = 'opaque';

        // Insert SWF
        swfload('vplay', 'vplayswf', swfUrl, '100%', '100%', { xml_path: '/data/player_default_config.xml', allow_share: $allowSharing }, { wmode: wm, allowscriptaccess: 'always' });

        if (!window.ie6)
            $vplayBG.css('opacity', __opacity / 100);
        else
            $vplayBG.css('filter', 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + __opacity + ')');
    }

    // set vplayer (bg,container) to be seen
    _$('vplayContainer').style.display = 'block';
    _$('vplayBG').style.display = 'block';


    // set vplayer (bg,container,self) to current viewable area
    var h = window.getHeight();
    var w = window.getWidth();

    _$('vplayContainer').style.height = h + 'px';
    _$('vplayContainer').style.width = w + 'px';
    _$('vplay').style.height = h + 'px';
    _$('vplay').style.width = w + 'px';
    if (window.ie6)
    {
        _$('vplayBG').style.height = h + 'px';
        _$('vplayBG').style.width = w + 'px';
    }

    if (window.ie6)
    { 								// ie 6 specific stuff to remove scrolling
        __winHeight = parseInt($(window).height()); // the full height of the scrollable content
        _$('vplayContainer').style.top = parseInt($(window).scrollTop()) + 'px';
    }
    var $flash = $('#vplayswf');
    if ($flash.length > 0 && $flash[0].setGuid)
        $flash[0].setGuid(videoGuid, sortCat, showNextPrev, $baseUrl, namodelCodeQS);
    //    } catch (e) { }
};

function goIplay(swfUrl, imageGuid, sortCat, showNextPrev, baseUrl, namodelCodeQS, startSlideshow, srui)
{
    $startSlideshow = startSlideshow;
    $serviceUri = (srui != undefined && srui != null) ? srui : 'default';
    $mediaType = 'image';
    $allowSharing = true;

    if (!IsFlashSupported() || MEDIA_GALLERY_USE_HTML_SLIDESHOW)
    {
        StartHtmlSlideshow(imageGuid, sortCat, showNextPrev, $allowSharing, baseUrl, namodelCodeQS, $mediaType, $serviceUri);
    }
    else
    {
        goVplay(swfUrl, imageGuid, sortCat, showNextPrev, $allowSharing, baseUrl, namodelCodeQS, $mediaType, $serviceUri);
    }
};

function StartHtmlSlideshow(imageGuid, sortCat, showNextPrev, allowSharing, baseUrl, namodelCodeQS, $mediaType, serviceUri)
{
    var category = sortCat.split("&")[1].split("=")[1];
    var naModelCode = namodelCodeQS.split("=")[1];
    var showNextPrev = showNextPrev ? "1" : "0";

    slideshowShareLink = window.location.href;
    if (slideshowShareLink.indexOf('#') == slideshowShareLink.length - 1)
    {
        slideshowShareLink = slideshowShareLink.substr(0, slideshowShareLink.length - 1);
        slideshowShareLink += "?namodelcode=" + naModelCode + "&imageguid={0}&" + sortCat;
    } 

    LoadSlideShow(imageGuid, category, showNextPrev, allowSharing, naModelCode);
}

function LoadSlideShow(imageGuid, category, showNextPrev, allowSharing, naModelCode)
{
    selectedImageGuid = imageGuid;

    var url = imageDataURL + "GetImageData/" + imageGuid + "/0/" + category + "/" + naModelCode + "/" + showNextPrev;
    $.getJSON(url + "?callbackName=?",
        function (data)
        {
            ProcessImageData(data);
        });
}

function ProcessImageData(imageData)
{
    var slideshowDiv = "<div id='slideshowContainer' style='width:" + slideshowBaseWidth + "px; height:" + slideshowBaseHeight + "px; background-color:#ffffff; border:solid 1px #cccccc;'>";
    slideshowDiv += "<div id='slideshowHeader' style='width:714px;padding:10px 0px 10px 15px;float:left;'>";
    slideshowDiv += "<div id='slideshowTitle' style='font-weight:bold;font-size:13px;'>Title</div>";
    slideshowDiv += "<div id='slideshowDescription' style='padding:0 0 0 0;font-size:13px;'>Description</div>";
    slideshowDiv += "</div>";
    slideshowDiv += "<div style='float:left;padding:15px 15px 0 0;'><a id='slideshowClose' href='#' class='linkPlain' onclick='OnClose();'><img src='" + ssCloseButton + "' /></a></div>";
    slideshowDiv += "<div class='clearBoth' />";
    slideshowDiv += "<div id='slideshow' style='height:335px;'>";

    images = imageData.Images;

    var startingSlide = 0;

    for (i = 0; i < imageData.Images.length; i++)
    {
        if (selectedImageGuid == imageData.Images[i].Guid)
        {
            startingSlide = i;
        }

        var wallpaperAvailable = imageData.Images[i].AspectRatios.length > 0;

        slideshowDiv += "<img src='" + imageData.Images[i].ImageUrl + "' title='" + imageData.Images[i].Title + "' alt='" + imageData.Images[i].Description + "' wallpaper='" + wallpaperAvailable + "' guid='" + imageData.Images[i].Guid + "' style='height:335px' />";
    }

    slideshowDiv += "</div>";

    slideshowDiv += "<div id='downloadTray' style='height:60px;position:relative;margin-top:-68px;padding:4px 20px;z-index:99;background:#fff;border-bottom:solid 1px #ccc;'>";
    slideshowDiv += "</div>";

    slideshowDiv += "<div id='shareTray' style='height:148px;position:relative;margin-top:-156px;padding:4px 20px;z-index:99;background:#fff;border-bottom:solid 1px #ccc;'>";
        slideshowDiv += "<div style='float:left;padding-right:35px;'><a id='shareSocial' href='#' onclick='OnShareSocial();'>Social</a></div>";
        slideshowDiv += "<div style='float:left;padding-right:35px;'><a id='shareEmail' href='#' onclick='OnShareEmail();'>Email</a></div>";
        slideshowDiv += "<div style='float:left;padding-right:35px;'><a id='shareEmbed' href='#' onclick='OnShareEmbed();'>Embed</a></div>";
        slideshowDiv += "<div class='clearBoth' />";
        slideshowDiv += "<div id='traySocial' style='padding-top:20px;display:none;'>";
            slideshowDiv += "<div id='socialForm' style='display:none;'>";
                slideshowDiv += "<div>To bookmark this image, or to include an image link on your preferred social networking site, click one of the options below. A new window will appear, allowing you to post the url to the relevant site.</div>";
                slideshowDiv += "<div style='float:left;padding:20px 0 20px 0;width:100px;' class='bold'>Bookmark</div><div style='float:left;padding-top:20px;' class='bold'>Add to social networking site</div><div style='clear:both' />";
                slideshowDiv += "<div style='float:left;padding-right:30px;'><a id='shareDigg' href='#' class='linkPlain' onclick='OnShareDigg();'><img src='" + ssDiggIcon + "'></a></div>";
                slideshowDiv += "<div style='float:left;padding-right:30px;'><a id='shareTwitter' href='#' class='linkPlain' onclick='OnShareTwitter();'><img src='" + ssTwitterIcon + "'></a></div>";
                slideshowDiv += "<div style='float:left;padding-right:30px;'><a id='shareFacebook' href='#' class='linkPlain' onclick='OnShareFacebook();'><img src='" + ssFacebookIcon + "'></a></div>";
            slideshowDiv += "</div>";
        slideshowDiv += "</div>";
        slideshowDiv += "<div id='trayEmail' style='padding-top:20px;display:none;'>";
            slideshowDiv += "<div id='emailForm' style='display:none;'>";
                slideshowDiv += "To share this image with a friend, complete the form below. All fields are required.<br />";
                slideshowDiv += "<div style='float:left; width:100px;padding:4px;'>Your Email</div><div style='float:left;'><input id='txtYourEmail' type='email' name='txtYourEmail' style='width:200px;' /></div><div id='valYourEmail' class='Alert' style='float:left; width:300px;padding:4px;'></div><div style='clear:both' />";
                slideshowDiv += "<div style='float:left; width:100px;padding:4px;'>Recipient's Email</div><div style='float:left;'><input id='txtRecipientEmail' type='email' name='txtRecipientEmail' style='width:200px;' /></div><div id='valRecipientEmail' class='Alert' style='float:left;padding:4px; width:300px;'></div><div style='clear:both' />";
                slideshowDiv += "<div style='float:left; width:100px;padding:4px;'>Your Message</div><div style='float:left;'><input id='txtMessage' type='text' name='txtMessage' style='width:200px;' /></div><div id='valMessage' class='Alert' style='float:left; width:300px;padding:4px;'></div><div style='clear:both' />";
                slideshowDiv += "<div style='float:left; width:247px;padding:4px;'>&nbsp;</div><div style='float:left;'><a href='#' class='jQueryBMWButton' onclick='OnSendEmail();'>Send</a></div>";
            slideshowDiv += '</div>';
            slideshowDiv += "<div id='emailThanks' style='padding:8px;display:none;'>";
                slideshowDiv += "Thank you for your interest. Your e-mail has been sent.<div style='clear:both' />";
                slideshowDiv += "<a id='sendAnotherEmail' href='#' onclick='OnShareEmail();'>E-mail another friend</a><div style='clear:both' />";
                slideshowDiv += "<a id='signupForMyBMW' href='" + REGISTRATION_URL + "'>Sign up for a My BMW account</a><div style='clear:both' />";
            slideshowDiv += '</div>';
        slideshowDiv += "</div>";
        slideshowDiv += "<div id='trayEmbed' style='padding-top:20px;display:none;'>";
            slideshowDiv += "<div>Copy this code to your website or blog.</div>";
            slideshowDiv += "<div style='float:left;padding-top:20px;width:349px;padding-right:10px;'>";
                slideshowDiv += "<div style='width:349px;' class='bold'>Embed:</div>";
                slideshowDiv += "<div style='width:349px;'><textarea id='txtEmbed' name='txtEmbed' style='width:339px;height:50px;' readonly='true'>" + slideshowShareLink + "</textarea></div>";
                //slideshowDiv += "<a id='copyEmbedToClipboard' href='#' onclick='onCopyEmbedToClipboard();'>Copy to clipboard</a>";
            slideshowDiv += "</div>";
            slideshowDiv += "<div style='float:left;padding-top:20px;width:349px;padding-left:10px;'>";
                slideshowDiv += "<div class='bold'>Direct URL:</div>";
                slideshowDiv += "<div style='width:349px;'><textarea id='txtLink' name='txtLink' style='width:339px;height:50px;' readonly='true'>" + slideshowShareLink + "</textarea></div>";
                //slideshowDiv += "<a id='copyLinkToClipboard' href='#' onclick='onCopyLinkToClipboard();'>Copy to clipboard</a>";
            slideshowDiv += "</div>";
        slideshowDiv += "</div>";
    slideshowDiv += "</div>";
    slideshowDiv += "<div id='slideshowController' style=\"height:44px; padding:6px 0px 6px 20px; background-image: url('" + ssControllerBackground + "');background-repeat:repeat-x;\">";
        slideshowDiv += "<div style='float:left;width:359px;'>";
            slideshowDiv += "<div style='float:left;width:32px;'>";
            slideshowDiv += "<a id='slideshowPlay' href='#' class='linkPlain' style='font-size:14px;font-weight:bold;' onclick='OnPlayPause();'><img id='playPauseButton' src='" + ssPlayButton + "' /></a>";
            slideshowDiv += "</div>";
            slideshowDiv += "<div style='float:left;width:275px;padding-left:10px;padding-top:8px;'>";
            slideshowDiv += "<a id='playPauseText' href='#' class='linkPlain' style='font-size:14px;font-weight:bold;' onclick='OnPlayPause();'>Play</a>";
            slideshowDiv += "</div>";
            slideshowDiv += "<div style='float:left;'>";
            slideshowDiv += "<a id='prev' href='#' class='linkPlain' onclick='OnPrev();'><img id='prevButton' src='" + ssPrevButton + "' style='padding-right:10px;' /></a>";
            slideshowDiv += "</div>";
        slideshowDiv += "</div>";
        slideshowDiv += "<div style='float:left;width:359px;'>";
            slideshowDiv += "<div style='float:left;width:32px;padding-left:10px;'>";
            slideshowDiv += "<a id='next' href='#' class='linkPlain' onclick='OnNext();'><img id='nextButton' src='" + ssNextButton + "' /></a>";
            slideshowDiv += "</div>";
            slideshowDiv += "<div id='slideshowDownload' style='visibility:hidden;' >";
                slideshowDiv += "<div style='float:left;width:172px;padding-right:10px;padding-top:8px;text-align:right;'>";
                slideshowDiv += "<a id='downloadText' href='#' class='linkPlain' style='font-size:14px;font-weight:bold;' onclick='OnDownload();'>Download Wallpaper</a>";
                slideshowDiv += "</div>";
                slideshowDiv += "<div style='float:left;'>";
                slideshowDiv += "<a id='download' href='#' class='linkPlain' style='font-size:14px;font-weight:bold;' onclick='OnDownload();'><img id='downloadButton' src='" + ssDoubleArrowUpButton + "' /></a>";
                slideshowDiv += "</div>";
            slideshowDiv += "</div>";
            slideshowDiv += "<div style='float:left;padding-left:20px;padding-top:8px;'>";
            slideshowDiv += "<a id='shareText' href='#' class='linkPlain' style='font-size:14px;font-weight:bold;' onclick='OnShare();'>Share</a>";
            slideshowDiv += "</div>";
            slideshowDiv += "<div style='float:left;padding-left:10px;'>";
            slideshowDiv += "<a id='share' href='#' class='linkPlain' style='font-size:14px;font-weight:bold;' onclick='OnShare();'><img id='shareButton' src='" + ssDoubleArrowUpButton + "' /></a>";
            slideshowDiv += "</div>";
        slideshowDiv += "</div>";
    slideshowDiv += "</div>";
    slideshowDiv += "</div>";

    $('body').append(slideshowDiv);
    $('#shareTray').hide();
    $('#downloadTray').hide();

    var top = (window.innerHeight - 425) / 2;
    var left = (window.innerWidth - 758) / 2;

//    console.log('Start');
//    console.log('window.pageXOffset = ' + window.pageXOffset);
//    console.log('window.pageYOffset = ' + window.pageYOffset);
//    console.log('$(window).height() = ' + $(window).height());
//    console.log('$(window).width() = ' + $(window).width());
//    console.log('window.innerHeight = ' + window.innerHeight);
//    console.log('window.innerWidth = ' + window.innerWidth);
//    console.log('top = ' + top);
//    console.log('left = ' + left);
//    console.log('End');

    $.blockUI({
        message: $('#slideshowContainer'),
        css: {
            top: top,
            left: left,
            width: $('#slideshowContainer').width() + "px",
            border: '1px solid #eee',
            textAlign: 'left',
            cursor: 'arrow'
        },
        overlayCSS: { "backgroundColor": "#fff" },
        onUnblock: OnUnblock()
    });

    $('.blockUI.blockOverlay').height($(document).height() + 'px');

    $('#slideshow').cycle({
        fx: 'fade',
        timeout: 5000,
        startingSlide: startingSlide,
        requeueOnImageNotLoaded: false,
        requeueTimeout: 10000,
        before: OnBefore
    }).cycle('pause');

    $("#slideshow").touchwipe({
        wipeLeft: function () { OnNext(); },
        wipeRight: function () { OnPrev(); },
        wipeUp: function () { },
        wipeDown: function () { },
        min_move_x: 20,
        min_move_y: 20,
        preventDefaultEvents: true
    });

    $(window).resize(function () { ResizeAndCenter(); });
}

function OnSendEmail()
{
    var from = $('#txtYourEmail').val();
    var to = $('#txtRecipientEmail').val();
    var message = $('#txtMessage').val();

    $('#valYourEmail').html('');
    $('#valRecipientEmail').html('');
    $('#valMessage').html('');

    if (IsValidEmail(from) && IsValidEmail(to) && message.length > 0)
    {
        var link = slideshowShareLink.replace('{0}', slideshowCurrentImageGuid);
        var body = message + "<br/>" + link;
        var subject = "BMW Image Link: " + slideshowCurrentTitle;

        var url = imageDataURL + "SendEmail";
        var data = '{ "fromAddress": "' + from + '", "toAddress": "' + to + '", "subject": "' + subject + '", "body": "' + body + '", "priority": "0", "isHtml": "1" }';

        $.ajax({
            type: "POST",
            url: "/ImageData/ImageData.svc/SendEmail",
            data: data,
            contentType: "application/json",
            dataType: "json",
            success: function (data)
            {
                ProcessEmailResult(data);
            }
        });
    }
    else
    {
        if (!IsValidEmail(from))
        {
            $('#valYourEmail').html('You have entered an invalid from e-mail address.');
        }

        if (!IsValidEmail(to))
        {
            $('#valRecipientEmail').html('You have entered an invalid to e-mail address.');
        }

        if (message.length == 0)
        {
            $('#valMessage').html('Please enter a message.');
        }
    }
}

function IsValidEmail(email)
{
    var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;

    return filter.test(email);
}

function ProcessEmailResult(result)
{
    $('#emailForm').hide();
    $('#txtYourEmail').val('');
    $('#txtRecipientEmail').val('');
    $('#txtMessage').val('');
    $('#emailThanks').show();
}

function OnShare()
{
    PauseSlideShow();
    CollapseDownloadTray();
    ToggleShareTray();
    OnShareSocial();
}

function OnDownload()
{
    PauseSlideShow();
    CollapseShareTray();
    ToggleDownloadTray();
}

function OnShareDigg()
{
    var link = slideshowShareLink.replace('{0}', slideshowCurrentImageGuid);
    window.open('http://digg.com/submit?phase=2&url=' + link, 'mywindow');
}

function OnShareTwitter() 
{
    var link = slideshowShareLink.replace('{0}', slideshowCurrentImageGuid).replace('1.255.11.193', 'www.bmwusa.com');
    window.open('http://twitter.com/intent/tweet?text=' + encodeURIComponent(document.title) + "&url=" + encodeURIComponent(link));
}

function OnShareFacebook()
{
    var link = slideshowShareLink.replace('{0}', slideshowCurrentImageGuid).replace('1.255.11.193', 'www.bmwusa.com');
    window.open('http://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(link) + '&t=' + encodeURIComponent(document.title), 'mywindow');
}

function ToggleShareTray()
{
    if ($('#shareTray').is(':visible'))
    {
        CollapseShareTray();
    }
    else
    {
        ExpandShareTray();
    }
}

function CollapseShareTray()
{
    $('#shareButton').attr("src", ssDoubleArrowUpButton);
    $('#shareTray').hide();
    $('#traySocial').hide();
    $('#trayEmail').hide();
    $('#trayEmbed').hide();
}

function ExpandShareTray()
{
    $('#shareButton').attr("src", ssDoubleArrowDownButton);
    $('#traySocial').show();
    $('#shareTray').show();
}

function ToggleDownloadTray()
{
    if ($('#downloadTray').is(':visible'))
    {
        CollapseDownloadTray();
    }
    else
    {
        ExpandDownloadTray();
    }
}

function CollapseDownloadTray()
{
    $('#downloadButton').attr("src", ssDoubleArrowUpButton);
    $('#downloadTray').hide();
}

function ExpandDownloadTray()
{
    $('#downloadButton').attr("src", ssDoubleArrowDownButton);

    var wallpaperDiv = '';
    var widescreenUrl = '';
    var standardscreenUrl = '';

    // add content to tray
    for (i = 0; i < images.length; i++)
    {
        if (slideshowCurrentImageGuid == images[i].Guid)
        {
            for (wp = 0; wp < images[i].AspectRatios.length; wp++)
            {
                if (images[i].AspectRatios[wp].Ratio == '4:3')
                {
                    standardscreenUrl = images[i].AspectRatios[wp].ImageUrl;
                }

                if (images[i].AspectRatios[wp].Ratio == '16:9')
                {
                    widescreenUrl = images[i].AspectRatios[wp].ImageUrl;
                }
            }
        }
    }

    wallpaperDiv += "<div>";
        wallpaperDiv += "<div style='float:left;width:100px;'>";
        wallpaperDiv += "<div class='bold'>Standard Screen</div>";

            wallpaperDiv += "<div><a href='" + standardscreenUrl.replace('.arox', '_@1024x768.arox') + "'>1024x768</a></div>";
            wallpaperDiv += "<div><a href='" + standardscreenUrl.replace('.arox', '_@1400x1050.arox') + "'>1400x1050</a></div>";
            wallpaperDiv += "<div><a href='" + standardscreenUrl.replace('.arox', '_@1600x1200.arox') + "'>1600x1200</a></div>";
        wallpaperDiv += "</div>";
        wallpaperDiv += "<div style='float:left;width:100px;'>";
            wallpaperDiv += "<div class='bold'>Widescreen</div>";
            wallpaperDiv += "<div><a href='" + widescreenUrl.replace('.arox', '_@1280x800.arox') + "'>1280x800</a></div>";
            wallpaperDiv += "<div><a href='" + widescreenUrl.replace('.arox', '_@1680x1050.arox') + "'>1680x1050</a></div>";
            wallpaperDiv += "<div><a href='" + widescreenUrl.replace('.arox', '_@1920x1200.arox') + "'>1920x1200</a></div>";
        wallpaperDiv += "</div>";
    wallpaperDiv += "</div>";

    $('#downloadTray').html(wallpaperDiv);
    $('#downloadTray').show();
}

function ResizeAndCenter()
{
    var top = (window.innerHeight - 425) / 2;
    var left = (window.innerWidth - 758) / 2;

//    console.log('Start');
//    console.log('window.pageXOffset = ' + window.pageXOffset);
//    console.log('window.pageYOffset = ' + window.pageYOffset);
//    console.log('$(window).height() = ' + $(window).height());
//    console.log('$(window).width() = ' + $(window).width());
//    console.log('window.innerHeight = ' + window.innerHeight);
//    console.log('window.innerWidth = ' + window.innerWidth);
//    console.log('top = ' + top);
//    console.log('left = ' + left);
//    console.log('End');

    $('.blockUI.blockMsg.blockPage').animate({
        top: top,
        left: left
    }, 500);
}

function OnShareSocial()
{
    $('#traySocial').show();
    $('#trayEmail').hide();
    $('#trayEmbed').hide();
    $('#socialForm').show();
}

function OnShareEmail()
{
    $('#traySocial').hide();
    $('#trayEmbed').hide();
    $('#trayEmail').show();
    $('#emailForm').show();
    $('#emailThanks').hide();
    styleLinkAsButton();
    styleLinkAsStaticBMWButton();
}

function OnShareEmbed()
{
    $('#traySocial').hide();
    $('#trayEmail').hide();

    var link = slideshowShareLink.replace('{0}', slideshowCurrentImageGuid);
    var embed = slideshowShareEmbed.replace('{0}', link).replace('{1}', slideshowCurrentImageGuid);

    $('#txtEmbed').val(embed);
    $('#txtLink').val(link);
    $('#trayEmbed').show();
}

function OnClose()
{
    $('#slideshow').cycle('pause')
    //$('#slideshow').cycle({ timeout: 0, before: null });
    $.unblockUI();
}

function OnUnblock()
{
    $('#slideshow').cycle('destroy');
    $('#slideshowContainer').remove();
}

function OnNext()
{
    CollapseDownloadTray();
    PauseSlideShow();
    $('#slideshow').cycle('next');
}

function OnPrev()
{
    CollapseDownloadTray();
    PauseSlideShow();
    $('#slideshow').cycle('prev');
}

function OnPlayPause()
{
    CollapseShareTray();
    CollapseDownloadTray();

    if ($('#playPauseButton').attr("src") == ssPlayButton)
    {
        $('#playPauseButton').attr("src", ssPauseButton);
        $('#playPauseText').html("Pause");
        $('#slideshow').cycle('resume');
    }
    else
    {
        PauseSlideShow();
    }
}

function PauseSlideShow()
{
    $('#playPauseButton').attr("src", ssPlayButton);
    $('#playPauseText').html("Play");
    $('#slideshow').cycle('pause');
}

function OnBefore(current, next, options)
{
    $('#slideshowTitle').html(this.title);
    $('#slideshowDescription').html(this.alt);
    slideshowCurrentTitle = next.title;
    slideshowCurrentDescription = next.alt;
    slideshowCurrentImageGuid = $(next).attr('guid');

    if ($(next).attr('wallpaper') == 'true')
    {
        $('#slideshowDownload').css({ visibility: "visible" });
    }
    else
    {
        $('#slideshowDownload').css({ visibility: "hidden" });
    }
}

function goInline(swfUrl, videoGuid, sortCat, showNextPrev, allowSharing, baseUrl, namodelCodeQS, mediaType, serviceUri, divId)
{
    //baseUrl = encodeURIComponent(baseUrl);
    if (_$(divId + "_vplay") == null)
    {
        //make flashvars for initial - inline makes no use of saved vars (those reserved for modal nigleton player)

        var flashvars = { videoGuid: videoGuid,
            sortCat: sortCat,
            showNextPrev: showNextPrev,
            baseUrl: encodeURIComponent(baseUrl),
            namodelCodeQS: namodelCodeQS,
            mediaType: mediaType,
            serviceUri: serviceUri,
            allow_share: allowSharing,
            xml_path: 'http://content.bmwusa.com/microsite/vp/player_inline_config.xml',
            startSlideshow: $startSlideshow
        };

        swfload(divId, divId + "_vplay", swfUrl, '100%', '100%', flashvars, { wmode: 'transparent', allowscriptaccess: 'always' });
        $inlinePlayers[divId + "_vplay"] = "active";

    } else
    {
        var isnull = false;
        var swfid = divId + '_vplay';
        var $flash = $('#' + swfid);

        if ($('#' + swfid) != null)
        {
            $flash[0].setGuid(videoGuid, sortCat, showNextPrev, baseUrl, namodelCodeQS, allowSharing, serviceUri);
        }

        //Talk to embedded swf here...
    }
};



// API: Flash calls this function to retreive current params
function getVplayID()
{ // send to flash if requested
    return [$videoGuid, $sortCat, $showNextPrev, $allowSharing, $baseUrl, $namodelCodeQS, $mediaType, $serviceUri, $startSlideshow];
}



// API: Call from JS or Flash to handle closing of the video player
// If called from JavaScript/HTML then fromJS must be set to true
// so that a call to Flash can be made to stop videos and transition out
function noVplay(fromJS)
{
    //    try {
    fromJS = fromJS == null ? false : fromJS;
    var $vplayswf = _$('vplayswf')
    _$('vplayContainer').style.height = 0;
    _$('vplayBG').style.height = 0;
    if ((!fromJS && window.ie6) || ($vplayswf.closeVideo == null && fromJS && window.ie6))
        toggleSelects('on');
    if (fromJS && $vplayswf.closeVideo != null)
        $vplayswf.closeVideo();
    //    } catch (e) { }
}
function pauseAllInlineVideos()
{
    for (var key in $inlinePlayers)
    {
        var obj = $inlinePlayers[key];
        if (_$(key) != null)
        {
            var swfid = key;
            var $flash = $('#' + key);
            $flash[0].pause();
        }
    }
}
// API (possible future enhancement): Tell Flash to pause Video
function pauseVideo(divId)
{
    if (divId == null)
    {
        //assumes modal
        var $flash = $('#vplayswf');
        if ($flash.length > 0 && $flash[0].setGuid)
        {
            $flash[0].pause()
        };
    } else
    {
        //
        if (_$(divId + "_vplay") != null)
        {
            var swfid = divId + '_vplay';
            var $flash = $('#' + swfid);
            $flash[0].pause();
        }
    }
}
// API (possible future enhancement): Tell Flash to resume/play Video
function resumeVideo(divId)
{
    if (divId == null)
    {
        //assumes modal
        var $flash = $('#vplayswf');
        if ($flash.length > 0 && $flash[0].setGuid)
        {
            $flash[0].resume()
        };
    } else
    {
        //
        if (_$(divId + "_vplay") != null)
        {
            var swfid = divId + '_vplay';
            var $flash = $('#' + swfid);
            $flash[0].resume();
        }
    }
}
// API (possible future enhancement): Tell Flash to set auto play
function setAutoPlay()
{
}

// EVENTS
// Window Event to resize the player area based on the Viewable area.
function resizeVplay()
{
    //    try {
    var $vplayBG = $('#vplayBG');
    var $vplay = $('#vplayContainer');
    var $vplayInner = $('#vplay');
    var $vplayswf = $('#vplayswf');

    var h = window.getHeight();
    var w = window.getWidth();

    if ($vplay != null && parseInt($vplay.css('height')) > 1 && $vplayswf != null)
    {
        if (window.ie6)
        {
            $vplayBG.css('height', h + 'px');
            $vplayBG.css('width', w + 'px');
            $vplay.css('top', parseInt($(window).scrollTop()) + 'px');
        }
        $vplay.css('height', h + 'px');
        $vplay.css('width', w + 'px');
        $vplayInner.css('height', h + 'px');
        $vplayInner.css('width', w + 'px');
    }
    //    } catch (e) { }
}

function scrollVplay()
{
    _$('vplayContainer').style.top = parseInt($(window).scrollTop()) + 'px';
    _$('vplayBG').style.top = parseInt($(window).scrollTop()) + 'px';
}

// Window events to handle styling of intitial and resized windows
$(document).ready(function ()
{
    try
    {
        if (window.ie6)
            if (_$('vplayswf') != null && parseInt(_$('vplayContainer').style.height) > 0) scrollVplay()

        resizeVplay();
        $(window.body).css('height', '100%');
        $(window.html).css('height', '100%');
    } catch (e) { }
});

$(document).ready(function ()
{
    $(window).resize(function () { resizeVplay(); });
    $ready = true;
});

function toggleSelects(offOrOn)
{
    try
    {
        var S = document.getElementsByTagName('SELECT');
        for (var i = 0, l = S.length; i < l; i++)
        {
            var s = S[i];
            var visi = offOrOn == 'off' ? 'hidden' : 'visible';
            s.style.visibility = visi;
        }
    } catch (e) { }
}

function IsFlashSupported()
{
    var hasFlash = false;

    if (navigator.plugins && navigator.plugins.length)
    {
        var plugin = navigator.plugins['Shockwave Flash'];
        if (plugin)
        {
            hasFlash = true;
        }

        if (navigator.plugins['Shockwave Flash 2.0'])
        {
            hasFlash = true;
        }

    }
    else if (navigator.mimeTypes && navigator.mimeTypes.length)
    {
        var mimeType = navigator.mimeTypes['application/x-shockwave-flash'];
        hasFlash = mimeType && mimeType.enabledPlugin;
    }
    else
    {
        try
        {
            // Try the default activeX
            var ax = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
            hasFlash = true;
        }
        catch (e)
        {
            // No flash
        }
    }

    return hasFlash;
}
