﻿/// <reference path="jquery-1.2.6.js"/>
/// <reference path="json2.js"/>
/// <reference path="Plugins/jquery.facebox.js"/>
/// <reference path="Plugins/jquery.shoprpop.js"/>
/// <reference path="Plugins/jquery.misc.utilities.js"/>

var defaultAskText = "Get help by asking a question or creating a list that your friends can fill with recommendations.";

//this file is included in most places. Add global code here.
jQuery(document).ready(function() {
    
    //for ie5 and ie6
    correctPNG();

});

function onUnFollowUserRemove(accid) {
    jQuery.ajaxDotNet(window.ShoprService + "UnFollowUser",
    {
        data: { pAccessorID: accid },
        success: function(o) {
            if (o != null) {
                jQuery('#mem_' + accid).fadeOut('10');
            }
        },
        error: onCommonError
    });
}

function onfollowUser(accid, intFollow) {

    var followFunction = "FollowUser";
    if (intFollow == 0)
        followFunction = "UnFollowUser";

    jQuery.ajaxDotNet(window.ShoprService + followFunction,
    {
        data: { pAccessorID: accid },
        success: function(o) {
            if (o != null) {
                var objmem = jQuery('#mem_' + accid);
                if (followFunction == "UnFollowUser") {
                    objmem.find('#followinglink').hide();
                    objmem.find('#followingbox').hide();
                    objmem.find('#followbox').fadeIn(4000);
                }
                else {
                    //if now following
                    objmem.find('#followinglink').fadeIn(2000);
                    objmem.find('#followinglinknotme').fadeIn(2000);
                    objmem.find('#followingbox').hide();
                    objmem.find('#followbox').hide();
                }
            }
        },
        error: onCommonError
    });
}

function onfollowUserProfile(accid, intFollow) {

    var followFunction = "FollowUser";
    if (intFollow == 0)
        followFunction = "UnFollowUser";

    jQuery.ajaxDotNet(window.ShoprService + followFunction,
    {
        data: { pAccessorID: accid },
        success: function(o) {
            if (o != null) {
                var objmem = jQuery('#followdiv');
                if (followFunction == "UnFollowUser") {
                    objmem.find('#followinglink').hide();
                    objmem.find('#followingbox').hide();
                    objmem.find('#followbox').fadeIn(4000);
                }
                else {
                    //if now following
                    objmem.find('#followinglink').fadeIn(2000);
                    objmem.find('#followingbox').hide();
                    objmem.find('#followbox').hide();
                }
            }
        },
        error: onCommonError
    });
}

function onEmailSelectedForward() {
    var txtemail = document.getElementById('txtFollowEmail').value;

    var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    if (!emailPattern.test(txtemail)) {
        jQuery('#frecmes').html("Invalid email address");
        return false;
    }

    var strFriends = "<div class='frienditem' onclick='onRemoveSelectedEmail(this);'><div class='friendimage'><img src='/MemberImages/email25.gif'></div>";
    strFriends += "<div class='emailname'>Email:" + txtemail + "</div></div>";

    jQuery('#forwardsel').append(jQuery(strFriends.replace(/@/, "@ ")));
    document.getElementById('txtFollowEmail').value = "";
    jQuery('#frecmes').html("");
}

function getfeedback() {

    jQuery.ajaxDotNet(window.ShoprService + "GetFeedbackControl",
    {
        success: function(o) {
            if (o != null) {
                jQuery.facebox.settings.width = 700;
                jQuery.facebox(o.d);

                //catch if closed by clicking "ok" delete button
                jQuery().unbind('closeWithData.facebox');
                jQuery().bind('closeWithData.facebox', {}, function(e, data) {
                    var comment = jQuery('#txtFeedBackComment').val();
                    var type = document.getElementById('selectType').value;

                    if (comment == null || comment.length < 1) {
                        jQuery('#feedbackmessage').html('<span>Please explain the feedback in the space provided</span>');
                        return;
                    }

                    if (type == null || type < 1 || type == 'Select the type of feedback') {
                        jQuery('#feedbackmessage').html('<span>Please choose a feedback type</span>');
                        return;
                    }

                    sendFeedback(type, comment);
                });

            }
        },
        error: onCommonError
    });
}

function sendFeedback(feedbackTypeID, message) {

    jQuery.ajaxDotNet(window.ShoprService + "AddFeedback",
    {
        data: { feedbackTypeID: feedbackTypeID, message: message },
        success: function(o) {
            if (o != null) {
                jQuery.facebox.close();
                displayFeedbackConfirmation();
            }
        },
        error: onCommonError
    });
}

function displayFeedbackConfirmation() {
    jQuery.ajaxDotNet(window.ShoprService + "GetFeedbackConfirmationControl",
    {
        data: {},
        success: function(o) {
            jQuery.facebox.settings.width = 600;
            jQuery.facebox(o.d);
            //jQuery.facebox.close();
        },
        error: onCommonError
    });
}

function onCommonError(o) {
    var str;
    if (o.responseText !== undefined) {
        str = "<li>Transaction id: " + o.tId + "</li>";
        str += "<li>HTTP status: " + o.status + "</li>";
        str += "<li>Status code message: " + o.statusText + "</li>";
        alert(str);
    }
}

function showfulldemo() {
    jQuery('#helpsection').hide();
    jQuery('#helptitle').show();
    jQuery('#helpvideo').show();
    jQuery('#helpsection').slideDown(300);
    jQuery('#demoupdown').attr("src", "/images/uparrow.png");
    jQuery.cookie('hidedemovideo', null, { path: '/' });
}
function showtitle() {
    jQuery('#helptitle').slideDown(300);
}
function showhidevideo() {
    var path = jQuery('#demoupdown').attr("src");
    if (path == "/images/uparrow.png") {
        jQuery('#demoupdown').attr("src", "/images/downarrow.png");
        hidevideo();
    }
    else {
        jQuery('#demoupdown').attr("src", "/images/uparrow.png");
        showvideo();
    }
}
function showvideo() {
    jQuery('#helpvideo').slideDown(300);
}
function hidevideo() {
    jQuery('#helpvideo').slideUp(300);
}
function closefulldemo() {
    jQuery('#helpsection').slideUp(300);
    jQuery('#demoupdown').attr("src", "/images/downarrow.png");
}
function dontshowdemo() {
    jQuery.cookie('hidedemovideo', 'true', { path: '/' });
    closefulldemo();
}

var ytplayer = null;
function onYouTubePlayerReady(playerId) {
    ytplayer = document.getElementById('shoprytplayer');
    playYouTube();
}

function playYouTube() {
    if (ytplayer) {
        ytplayer.playVideo();
    }
}

function clearVideo() {
    if (ytplayer) {
        ytplayer.stopVideo();
        ytplayer.clearVideo();
        ytplayer = null;
    }
    jQuery('#playercontainer').children().remove();
    
}

function replaceVideo(vid) {
    alert(vid);
    clearVideo();
    loadNewDemo(vid);
}

function loadNewDemo(vid) {

    jQuery('#playercontainer').append("<div id='ytapiplayer'>You need Flash player 8+ and JavaScript enabled to view this video.</div>");
    
    var params = { allowScriptAccess: "always", bgcolor: "#cccccc", quality: "high", scale:"exactfit", allowfullscreen: "true"  };
    var atts = { id: "shoprytplayer" };
    swfobject.embedSWF("http://www.youtube.com/v/" + vid + "&hl=en&fs=1&enablejsapi=1&playerapiid=ytplayer",
                       "ytapiplayer", "480", "385", "9", null, null, params, atts);

}

function loadYouTubeDemo(vid) {
    jQuery.facebox("<div id='playercontainer' style='width:481px; height:386px;'><div id='ytapiplayer'>You need Flash player 8+ and JavaScript enabled to view this video.</div></div>");

    clearVideo();
    loadNewDemo(vid);    

    jQuery().unbind('close.facebox');
    jQuery().bind('close.facebox', {}, function(e) {
        clearVideo();
        jQuery.facebox.closeNoEvent();
    });
}

//ImageRollSetup(sPath, sOvrSuffix, sFileExt, sImgEleId[, ...])
//example: ImageRollSetup('/images/buttons/', '_over', '.gif', 'button1', 'button2');
//each passed in image must have another image with suffix example ->  "...../button1_over.gif" and "...../button2_over.gif"
//function ImageRollSetup(p, s, x) {
//    var ele, id;
//    for (var i = 3; i < arguments.length; ++i) {
//        id = arguments[i];
//        if (ele == xGetElementById(id)) {
//            ele.xIOU = p + id + x;
//            ele.xIOO = new Image();
//            ele.xIOO.src = p + id + s + x;
//            ele.onmouseout = imgOnMouseout;
//            ele.onmouseover = imgOnMouseover;
//        }
//    }
//    function imgOnMouseout(e) {
//        if (this.xIOU) {
//            this.src = this.xIOU;
//        }
//    }
//    function imgOnMouseover(e) {
//        if (this.xIOO && this.xIOO.complete) {
//            this.src = this.xIOO.src;
//        }
//    }
//}

//function setupCategories(){

//    jQuery('.catitem').mouseover(function() {
//    jQuery(this).addClass('catitemon');
//    jQuery(this).find('.catsublist').show();

//});

//jQuery('.catitem').mouseout(function() {
//    jQuery(this).removeClass('catitemon');
//    jQuery(this).find('.catsublist').hide();
//});
//}


/**
*This methos should be included in all pages where png image is displayed. 
*This is to fix the transparency issue in ie. Call this function onload event of all jsps
**/
function correctPNG() {// correctly handle PNG transparency in Win IE 5.5 & 6.
    if (navigator.appVersion.indexOf("MSIE") >= 0) {
        var arVersion = navigator.appVersion.split("MSIE")
        var version = parseFloat(arVersion[1])
        if ((version >= 5.5 && version < 7.0) && (document.body.filters)) {

            for (var i = 0; i < document.images.length; i++) {
                var img = document.images[i]
                var imgName = img.src.toUpperCase()
                if (imgName.substring(imgName.length - 3, imgName.length) == "PNG") {
                    var imgID = (img.id) ? "id='" + img.id + "' " : ""
                    var imgClass = (img.className) ? "class='" + img.className + "' " : ""
                    var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
                    var imgStyle = "display:inline-block;" + img.style.cssText
                    if (img.align == "left") imgStyle = "float:left;" + imgStyle
                    if (img.align == "right") imgStyle = "float:right;" + imgStyle
                    if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
                    var strNewHTML = "<span " + imgID + imgClass + imgTitle
              + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
              + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
              + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
                    img.outerHTML = strNewHTML
                    i = i - 1
                }
            }
        }
    }
}

function clickInSearch() {
    var el = document.getElementById("txtTopSearchBox");
    jQuery(el).css('color', '#000000');

    if (el.value.substr(0, 6) == "Search")
        el.value = "";
}

function leaveSearch() {
    var el = document.getElementById("txtTopSearchBox");
    if (el.value.length < 1) {
        jQuery(el).css('color', '#999999');

        if (seachTopSelected == 1)
            el.value = "Search for people";
        else
            el.value = "Search for products";
    }
}

function expandAsk() {
    var el = document.getElementById("txtAsk");
    jQuery(el).css('color', '#000000');

    if (el.value == defaultAskText) el.value = "";
//    if (el.value.substr(0, 18) == "Get help by asking")
//        el.value = "";
}

function closeAsk() {
    var el = document.getElementById("txtAsk");
    if (el.value.length < 1) {
        el.value = defaultAskText;  // "Get help by asking a question or creating a list that your friends can fill with recommendations.";
        jQuery(el).css('color', '#666666');
        //jQuery('#txtAsk').css('display', 'none');
    }
}

function onSearch() {
    return onCommonSearch(seachSelected, '#txtSearchBox');
}

function onTopSearch() {
    return onCommonSearch(seachTopSelected, '#txtTopSearchBox');
}

function onCommonSearch(searchIndex, searchBoxID) {
    switch (searchIndex) {
        case 0: return onItemSearch(jQuery(searchBoxID).val()); break;
        case 1: return onUserSearch(jQuery(searchBoxID).val()); break;
        case 2: return onQuestionSearch(jQuery(searchBoxID).val()); break;
    }
}

function onItemSearch(s) {
    if (s.length < 1 || s.substr(0, 10) == "Search for") {
        alert("Please enter your search query in the search box.");
        return false;
    }

    window.location.href = '/search/' + escape(s) + "/";
    return false;
}

function onUserSearch(s) {
    if (s.length < 1 || s.substr(0, 10) == "Search for") {
        alert("Please enter your search query in the search box.");
        return false;
    }

    window.location.href = '/usersearch/' + escape(s) + "/";
    return false;
}

function onQuestionSearch(s) {
    if (s.length < 1 || s.substr(0, 10) == "Search for") {
        alert("Please enter your search query in the search box.");
        return false;
    }

    window.location.href = '/questionsearch/' + escape(s) + "/";
    return false;
}

function getKeyCode(e) {
    var evt = (e) ? e : window.event;
    return (evt.charCode) ? evt.charCode : evt.keyCode;
}

function searchTopKeyPress(e) {
    return searchCommonKeyPress(e, seachTopSelected, '#txtTopSearchBox');
}

function searchKeyPress(e) {
    return searchCommonKeyPress(e, seachSelected, '#txtSearchBox');
}

function searchCommonKeyPress(e, searchTypeIndex, searchBoxID) {
    if (getKeyCode(e) == 13) {
        return onCommonSearch(searchTypeIndex, searchBoxID);
    }
}

function searchUserKeyPress(e) {
    if (getKeyCode(e) == 13) {
        return onUserSearch(jQuery('#txtSearchBox').val());
    }
}

function searchQuestionKeyPress(e) {
    if (getKeyCode(e) == 13) {
        return onQuestionSearch(jQuery('#txtSearchBox').val());
    }
}

function searchItemKeyPress(e) {
    if (getKeyCode(e) == 13) {
        return onItemSearch(jQuery('#txtSearchBox').val());
    }
}

function onCreateListOrQuestion(isList) {
    var s = jQuery('#txtAsk').val();
    var action = "/" + (isList ? "create" : "ask") + "/";
    if (s != defaultAskText) action += escape(s) + "/";
    else action += "+/";
    var isPrivate = jQuery("#questionListButtons div:visible")[0].id == "privateDiv";
    if (isPrivate) action += "private/";
    window.location = action;
}

var seachTopSelected = 0;

function onSearchTopSelect(index) {
    seachTopSelected = index;
    switch (index) {
        case 0:
            //document.getElementById("txtTopSearchBox").value = "Search for products";
            jQuery('#searchTopProducts').addClass('searchselected');
            jQuery('#searchTopPeople').removeClass('searchselected');
            jQuery('#searchTopQuestions').removeClass('searchselected');
            jQuery('#pointupTop').animate({ 'left': 98 });
            break;
        case 1:
            //document.getElementById("txtTopSearchBox").value = "Search for people";
            jQuery('#searchTopPeople').addClass('searchselected');
            jQuery('#searchTopProducts').removeClass('searchselected');
            jQuery('#searchTopQuestions').removeClass('searchselected');
            jQuery('#pointupTop').animate({ 'left': 175 });
            break;
        case 2:
            //document.getElementById("txtTopSearchBox").value = "Search for people";
            jQuery('#searchTopPeople').removeClass('searchselected');
            jQuery('#searchTopProducts').removeClass('searchselected');
            jQuery('#searchTopQuestions').addClass('searchselected');
            jQuery('#pointupTop').animate({ 'left': 250 });
            break;
    }

    var el = document.getElementById("txtTopSearchBox");

    if (el.value.substr(0, 6) == "Search") {
        var str = "Search for ";
        switch (seachTopSelected) {
            case 0: str += "products"; break;
            case 1: str += "people"; break;
            case 2: str += "questions"; break;
        }
        el.value = str;
        jQuery(el).css('color', '#999999');
    }
}

function cancelReturn(e) {
    if (getKeyCode(e) == 13) return false;
}

//javascript calls shoprisauth() for this;

function shoprauth() {return true;}
function shoprnotauth(){
    alert("You must be logged in to perform this action.");
    return false;
}