// BROWSER DETECTION
function Is() {
    var agent = navigator.userAgent.toLowerCase();
    this.major = parseInt(navigator.appVersion);
    this.minor = parseFloat(navigator.appVersion);
    this.ns = ((agent.indexOf('mozilla') != -1) && (agent.indexOf('spoofer') == -1) && (agent.indexOf('compatible') == -1) && (agent.indexOf('opera') == -1) && (agent.indexOf('webtv') == -1));
    this.ns2 = (this.ns && (this.major == 2));
    this.ns3 = (this.ns && (this.major == 3));
    this.ns4 = (this.ns && (this.major == 4));
    this.ns6 = (this.ns && (this.major >= 5));
    this.opera = (agent.indexOf("opera") != -1);
    this.opera5 = (this.opera && (agent.indexOf("msie 6") != -1));
    this.ie = (agent.indexOf("msie") != -1) && !this.opera;
    this.ie3 = (this.ie && (this.major < 4));
    this.ie4 = (this.ie && (this.major == 4) && (agent.indexOf("msie 5") == -1 && agent.indexOf("msie 6") == -1));
    this.ie5 = (this.ie && (this.major == 4) && (agent.indexOf("msie 5") != -1));
    this.ie6 = (this.ie && (this.major == 4) && (agent.indexOf("msie 6") != -1));
    this.ieX = (this.ie && !this.ie3 && !this.ie4);
    this.win = (agent.indexOf("win") != -1);
    this.mac = (agent.indexOf("mac") != -1);
    this.unix = (agent.indexOf("x11") != -1);
}

var is = new Is(); // Create a browser detection object

if (is.ie5) {
    document.write('<link type=\"text/css\" href=\"_css/ie5.css\" rel=\"stylesheet\">')
}

$(document).ready(function() {
	$("input:submit[value='Search']").click(function() { RedirectSearch($(".searchtextbox").attr("id")); return false; });
});

function terms(SiteCulturePathStaticPage) {
    window.open(SiteCulturePathStaticPage + '/tos.htm', 'terms', 'width=500, height=600, resizable=yes, scrollbars=yes');
}

function screenViewer(path) {
    window.open('/screenviewer.aspx?p=' + path, '', 'width=1045, height=768, resizable=yes, scrollbars=yes');
}

function giftHelp(SiteCulturePathStaticPage) {
    window.open(SiteCulturePathStaticPage + '/gifts.htm', 'gifts', 'width=630, height=600, resizable=yes, scrollbars=yes');
}

var punctuation = '.,;!? ';
function trunc(s, size) {
    if (!size)
        size = 20;

    if (s.length <= size)
        return s;

    var p = -1;

    for (var i = 0; i < size; i++)
        if (punctuation.indexOf(s.charAt(i)) != -1)
        p = i;

    if (p == -1)
        p = size - 1;

    return '' + s.substr(0, p) + '...';
}

//email mask
function publisher(alias, text) {
    var pubcontact = "<a href=\"mailto";
    pubcontact += ":" + alias + "@";
    pubcontact += "ign";
    pubcontact += ".com\"";
    pubcontact += ">" + text + "<";
    pubcontact += "/a>";
    document.write(pubcontact);
}

//Redirect Search Page
function RedirectSearch(searchTerm) {
	location.replace("/Search.aspx?SearchTerm=" + escape($('#' + searchTerm).val()));
}

function verificationPop() {
    window.open('/verification/ver.htm', 'ver', 'width=270, height=150, resizable=no, scrollbars=no');
}

var useRecs = false;
function displayRecs() {
    useRecs = true;
}

function GetQueryStringValue(url, key) {
    var index = url.indexOf('?');

    if (index > -1) {
        // Get querystring section
        var querystring = url.substr(index + 1);

        // Split into key/value pairs
        var queryStringItems = querystring.split('&');

        for (i in queryStringItems) {
            // Split each pair
            var keyValuePair = queryStringItems[i].split('=');

            if (keyValuePair[0] == key) {
                return keyValuePair[1];
            }
        }
    }

    return '';
}

//ESRB ratings
function GetProductRating(productID, skuSuffix) {
    var url = "/lab/ratings/GetProductRating.aspx?pid=" + productID + "&suffix=" + skuSuffix;

    $.getJSON(url, SetRating);
}

function SetRating(data) {
    var ratingDiv = $('#RatingDiv');
    var ratingImg = $('#RatingImage');
    var ratingName = $('#RatingName');
    var ratingDescriptors = $('#RatingDescriptors');
    var ratingInfo = $('#RatingInfo');

    if (data.RatingID > 0) {
        ratingImg.html('<img src="/_img/ratings/' + data.SystemName + '/med/' + data.RatingCode + '.gif" />');
        ratingName.html('<b>Rating:</b> ' + data.RatingName);
        ratingDescriptors.html(data.RatingDescriptors);
        ratingInfo.html(data.RatingInfo);
        ratingDiv.show();
    }
    else {
        ratingDiv.hide();
    }
}

//product reviews/ratings
var readerReviewUrl = "/jsonrequests/GetReaderReviews.aspx";
//Get score text
function GetScoreText(scoreTexts, score) {
    var scoreTextsArray = scoreTexts.split(",");
    var overallScoreText = scoreTextsArray[parseInt(score)];
    if (overallScoreText != null) {
        return overallScoreText;
    }
    return "";
}
//Gets the average rating information
function GetAverageRatingInfo(_scoreTexts, _productId, _gameId, _reviewType) {
    productd = _productId;
    gameId = _gameId;
    reviewType = _reviewType;

    $.getJSON(
	    readerReviewUrl,
	    { gameId: gameId, op: 0, pageSize: 1, page: 1, reviewType: reviewType },
	    function(jsonData) {
	        if (jsonData) {
	            if (jsonData.length > 0) {
	                var main = $('#AverageRatingsMain');
	                var divHtml = "";
	                divHtml += CreateAverageRatingHtml(jsonData[0], _scoreTexts);
	                //Updates the main div
	                main.html(divHtml);
	            }
	        }
	    }
	);

}

//Sets the Average rating
function CreateAverageRatingHtml(data, scoreTexts) {
    var dhtml = '';
    dhtml += '<div class="review_rating">';
    dhtml += '<div class="review_avgrtg">';
    dhtml += '<div class="avg_rating_txt">AVERAGE D2D USER RATINGS</div>';
    dhtml += '<div class="avg_score_txt"><span id="readerReviewsAverage" >' + data.OverallAverage + '</span>&nbsp;<span id="readerReviewsScoreText" Class="score_type_txt">' + GetScoreText(scoreTexts, data.OverallAverage) + '</span></div>'
    dhtml += '<div class="number_txt"><span id="readerReviewsTotal">' + data.TotalReviews + '</span>&nbsp;reader reviews</div>'

    return dhtml;
}
//Add Post Vote
function AddPostVote(postId, isPositive, totalVotes) {
    var postedVoteNote = $('#postedVoteNote');

    $.ajax({
        url: readerReviewUrl,
        type: "POST",
        data: "postId=" + postId + "&isPositive=" + isPositive + "&op=4",
        dataType: "json",
        error: function() {
            postedVoteNote.html("Vote unsuccessful!");
        },
        success: function(jsonData) {
            if (jsonData) {
                //If the total votes were not updated then say that the vote was unsucessful
                if (totalVotes == jsonData.TotalVotes) {
                    if (jsonData.HasVoted) {
                        postedVoteNote.html("You have already voted.");
                    }
                    else {
                        postedVoteNote.html("Vote unsuccessful!");
                    }
                }
                else {
                    postedVoteNote.html("Vote posted. Thanks! Results will not be immediately updated.");
                }
            }
            else {
                postedVoteNote.html("Vote unsuccessful!");
            }
        }
    });
}

//quicklook
var quickLookArray = new Object();
var quickLookDelay = 750;
var timeoutID = 0;
var quickLookUrl = "/lab/quicklook/quicklook.aspx";

function StartQuickLook(e, productID) {
    StartQuickLook(e, productID, 0, 0);
}

function StartQuickLook(e, productID, summaryLength) {
    StartQuickLook(e, productID, 0, summaryLength);
}

function StartQuickLook(e, productID, genreID, summaryLength) {
    getMousePos(e);
    timeoutID = setTimeout('GetQuickLook(' + productID + ', ' + genreID + ', ' + summaryLength + ')', quickLookDelay);
}

function CancelQuickLook() {
    clearTimeout(timeoutID);
}

function GetQuickLook(productID) {
    GetQuickLook(productID, 0, 0)
}

function GetQuickLook(productID, summaryLength) {
    GetQuickLook(productID, 0, summaryLength);
}

function GetQuickLook(productID, genreID, summaryLength) {
    var jsonData;

    if ('p' + productID in quickLookArray) {
        SetQuickLook(quickLookArray['p' + productID], productID, genreID, summaryLength)
        return;
    }

    // Could not find jsonData, we are now making the request
    //    var url = '/lab/quicklook/quicklook.aspx?pid=' + productID;

    //    new Ajax.Request(url, {
    //	    method: 'get',
    //	    onComplete: function(transport) {		
    //		    if (200 == transport.status) {
    //			    // creates object availability
    //			    jsonData = transport.responseText.evalJSON();
    //				
    //				// add data to array
    //				quickLookArray['p'+productID] = jsonData;
    //				
    //			    SetQuickLook(jsonData, productID, genreID, summaryLength)
    //				
    //		    } else {
    //			    
    //		    }
    //	    }
    //    });

    // Could not find jsonData, we are now making the request
    $.getJSON(quickLookUrl, { pid: productID }, function(jsonData) {
        if (jsonData) {
            // add data to array
            quickLookArray['p' + productID] = jsonData;
            SetQuickLook(jsonData, productID, genreID, summaryLength)
        }
    });
}

function SetQuickLook(jsonData, productID, genreID, summaryLength) {
    var quickLookDiv = $('#QuickLookDiv');
    var quicklook_title = $('#quicklook_title');
    var quicklook_flv = $('#quicklook_flv');
    var quicklook_summary = $('#quicklook_summary');
    var quicklook_readMore = $('#quicklook_readMore');
    var quicklook_price = $('#quicklook_price');
    var quicklook_moreinfo = $('#quicklook_moreinfo');
    var quicklook_add = $('#quicklook_add');
    var ratingImg = $('#QLRatingImage');
    var ratingName = $('#QLRatingName');
    var ratingDescriptors = $('#QLRatingDescriptors');
    var ratingInfo = $('#QLRatingInfo');

    // Set info
    if (jsonData) {
        // Update title
        quicklook_title.html(jsonData.Name);

        // Trim summary if too long
        if (summaryLength > 0 && jsonData.Summary.length > summaryLength) {
            quicklook_summary.html(jsonData.Summary.substring(0, summaryLength) + '...');
        }
        else {
            quicklook_summary.html(jsonData.Summary);
        }

        // Reduce decimal value to 2 places for currency
        quicklook_price.html('$' + jsonData.Price.toFixed(2));

        var productLink;
        // Check if we're using SEO links
        if (jsonData.SeoName.length > 0) {
            // Create SEO link
            if (genreID > 0) {
                productLink = 'http://' + document.domain + '/' + genreID + '/' + productID + '/product/' + jsonData.SeoName;
            }
            else {
                productLink = 'http://' + document.domain + '/' + productID + '/product/' + jsonData.SeoName;
            }
        }
        else {
            // Create regular link
            productLink = '/product.aspx?pid=' + ProductID + '&gid=' + genreID;
        }

        // Update links
        quicklook_readMore.attr("href", productLink);
        quicklook_moreinfo.attr("href", productLink);

        //update class for AddToCart/Preorder/ComingSoon button
        if (jsonData.Availability == "Available") {
            quicklook_add.attr("class", "addLg");
        }        
        else if (jsonData.Availability == "Preorder") {
            quicklook_add.attr("class", "preorderLg");
        }
        else if (jsonData.Availability == "Coming Soon") {
            quicklook_add.attr("class", "comingSoonLg2");
        }
        
        if (typeof AddToCartJsonUrl == 'undefined') {
            quicklook_add.attr("href", '/addtocart.aspx?pid=' + productID + '&gid=' + genreID);
        }
        else {
            quicklook_add.attr("href", "javascript:addProductToCart(" + productID + ", " + genreID + ");");
        }

        // Video variables        
        var mediaURL = 'mediaURL=http://videos.direct2drive.com/^0/' + jsonData.VideoLink + '_hi.flv';
        var mediaLink = 'mediaLink=' + productLink;
        var myFlashVars = mediaURL + '&' + mediaLink
        quicklook_flv.html('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="210" height="157" id="MyMovie" align="left"><param name="allowScriptAccess" value="always" /><param name="wmode" value="opaque" /><param name="movie" value="/Sites/RET/_swf/QuickLook/FLVPlaybackBasic.swf" /><param name="base" value="" /><param name="FlashVars" value="' + myFlashVars + '" /><param name="quality" value="high" /><param name="bgcolor" value="#000000" /><embed src="/Sites/RET/_swf/QuickLook/FLVPlaybackBasic.swf" base="" FlashVars="' + myFlashVars + '" quality="high" bgcolor="#000000" width="210" height="157" name="MyMovie" align="middle" wmode="opaque" allowScriptAccess="always" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object>');

        // Set Quick Look Product Rating
        ratingImg.html('<img src="/_img/ratings/' + jsonData.Rating.SystemName + '/small/' + jsonData.Rating.RatingCode + '.gif" />');
        ratingName.html('<b>Rating:</b> ' + jsonData.Rating.RatingName);
        ratingDescriptors.html(jsonData.Rating.RatingDescriptors);
        ratingInfo.html(jsonData.Rating.RatingInfo);

        // Position the div using the global mouse position
        quickLookDiv.css("top", mouseY + "px");
        quickLookDiv.css("left", mouseX + "px");

        // Show quicklook div
        quickLookDiv.show();
    }
    else {

    }
}

function HideQuickLook() {
    var quickLookDiv = $('#QuickLookDiv');
    var quicklook_flv = $('#quicklook_flv');

    // Hide div
    quickLookDiv.hide();

    // Clear video
    quicklook_flv.html('');
}

var mouseX;
var mouseY;
function getMousePos(e) {
    var IE = document.all ? true : false;

    if (IE) {
        mouseX = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
        mouseY = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    }
    else {
        if ($.browser.mozilla && $.browser.version == "1.9.0.1") {
            // bug fix for Firefox 3
            mouseX = e.pageX + 150;
            mouseY = e.pageY;
        }
        else {
            mouseX = e.pageX;
            mouseY = e.pageY;
        }
    }

    // Calculate to compensate positioning offsets created by divBody
    var mainDiv = document.getElementById('divBody');
    mouseX = mouseX - (mainDiv.offsetLeft + 50);
    mouseY = mouseY - (mainDiv.offsetTop + 300);
}

//domrollover
function domRollover() {
    if (navigator.userAgent.match(/Opera (\S+)/)) {
        var operaVersion = parseInt(navigator.userAgent.match(/Opera (\S+)/)[1]);
    }
    if (!document.getElementById || operaVersion < 7) return;
    var imgarr = document.getElementsByTagName('img');
    var imgPreload = new Array();
    var imgSrc = new Array();
    var imgClass = new Array();
    for (i = 0; i < imgarr.length; i++) {
        if (imgarr[i].className.indexOf('domroll') != -1) {
            imgSrc[i] = imgarr[i].getAttribute('src');
            imgClass[i] = imgarr[i].className;
            imgPreload[i] = new Image();
            if (imgClass[i].match(/domroll (\S+)/)) {
                imgPreload[i].src = imgClass[i].match(/domroll (\S+)/)[1]
            }
            imgarr[i].setAttribute('xsrc', imgSrc[i]);
            imgarr[i].onmouseover = function() {
                this.setAttribute('src', this.className.match(/domroll (\S+)/)[1])
            }
            imgarr[i].onmouseout = function() {
                this.setAttribute('src', this.getAttribute('xsrc'))
            }
        }
    }
}
domRollover();