﻿// JScript File

var sMax; // Isthe maximum number of stars
var holder; // Is the holding pattern for clicked state
var preSet; // Is the PreSet value onces a selection has been made
var rated;
var DisableButton = false;
var qsParm = new Array();
var albumNameBread;
var lastId = 0;
var presentID = 0;
var prevClick = 0;
var albumID;

var dfpTagAlbumName;


function trim(stringToTrim) {

    try {
        return stringToTrim.replace(/^\s+|\s+$/g, "");
    }
    catch (e) {
        return "";
    }
}


function fadeIn(id) {
    $("#" + id).fadeTo("fast", 1.0);
}

function fadeOut(id) {

    presentID = document.getElementById('picID').value;
    if (id != trim(presentID)) {
        $("#" + id).fadeTo("fast", 0.5);
        //       
        //        
    }

}

function FadeonClick(id) {

    id = trim(id);
    lastId = trim(lastId);

    if (lastId != id) {
        $("#" + id).fadeTo("fast", 1.0);

        presentID = document.getElementById('picID').value;

        $("#" + lastId).fadeTo("fast", 0.5);
        lastId = id;
    }



}



jQuery(document).ready(function() {
    jQuery('#mycarousel').jcarousel({
        scroll: 6,
        visible: 7.25,
        wrap: "both"
    });
    
    dfpTagAlbumName = document.getElementById("ctl00_ContentPlaceHolder1_dfpTagAlbumName").value;
    
    LoadQS();
    var imgID = qsParm['imgID'];
    var arID = (qsParm['arID']);
    albumID = (qsParm['abID']);
    var pgID = (qsParm['pageID']);
    document.getElementById('articleID').value = arID;
    document.getElementById('picID').value = imgID;
    if (albumID == "" || parseInt(albumID) < 0 || (isNaN(albumID)) || (isNaN(pgID)) || parseInt(pgID) < 0 || albumID == undefined) {
        document.getElementById("mainForm").style.display = "none";
        document.getElementById("msgDisplay").innerHTML = "No Photos in album";
        document.getElementById("msgDisplay").style.display = "Block";
    }
    else {
        document.getElementById('pgType').value = pgID;

        document.getElementById("JCarousel").style.visibility = "visible";
        //tb_reload();
        lastId = "0";
        if (imgID == "" || (isNaN(imgID)) || imgID == undefined || parseInt(imgID) < 0) {
            OnNext(getFirstImageId());
        } else {
            OnNext(imgID);
        }
    }
});

function parent_func_callback() {
    alert("test");

}
function OnNext(imgID) {
    var imageID = trim(imgID);
    //calling the click event of jcarosel event
    $("#" + imageID).click();
}

function rating(val, contentID, contentType) {
    IsAvailable = false;
    idList = checkCookie(contentID, contentType);
    var SplitList = idList.split(",");
    var i = 0;
    for (i = 0; i < SplitList.length; i++) {

        if (parseInt(SplitList[i]) == parseInt(contentID)) {
            IsAvailable = true;
            break;
        }
    }

    if (IsAvailable) {

        alert("You have already submitted this rating");
    }
    else {
        idList += "," + contentID;

        if (contentType == "1") {
            CookieName = "thumbs";

        }
        else if (contentType == "0") {
            CookieName = "Picture";

        }

        setCookie(CookieName, idList, 1);

        var pubType = 0;
        if (isCommunity())
            pubType = 1;

        $.ajax({
            url: 'GetData.asmx/rating',
            data: "rating=" + val + "&content_ID=" + contentID + "&content_Type=" + contentType + "&pub_type=" + pubType + "&user_IP=" + ipAddInfo,
            type: 'GET',
            processData: false,
            dataType: 'xmlDocument',
            timeout: 3000,
            error: function() {
                alert('Error loading XML document: rating');
            },
            success: function(xmlDocument) {
                getNodeValue(xmlDocument, "Rating", contentType);
            }
        });
    }


}

function RefreshAfterPost(picID) {

    //clearing the comment div and the comment inputbox
    document.getElementById('CommentDiv').innerHTML = "";
    document.getElementById('inputBox').value = "";
    //var albumID=(document.getElementById('<%= abID.ClientID%>').value );;
    var articleType = document.getElementById('articleID').value;
    var pgType = document.getElementById('pgType').value

    // If the page is community, pubType = 1, else pubType = 0
    var pubType = 0;
    if (isCommunity())
        pubType = 1;

    var xslParameters = null;
    if (isCommunity()) {
        xslParameters = new Array();
        xslParameters["community"] = "1";
    }

    $.ajax({
        //url of the webservice
        url: 'GetData.asmx/DisplayImgData',
        //parameters passes to the method
        data: "picID=" + picID + "&pgType=" + pgType + "&abID=" + albumID + "&arID=" + articleType + "&pub_type=" + pubType,
        type: 'GET',
        processData: false,
        //return type
        dataType: 'xmlDocument',
        //time afer which the webservice will time out
        timeout: 3000,
        //error handler
        error: function() {
            alert('Error loading XML document: RefreshAfterPost');
        },
        //success method
        success: function(xmlDocument) {
            //apply xsl to xml

            displayResult(xmlDocument, "/PhotoGallery/CommentStyle.xsl", "CommentDiv", xslParameters);
            var msg = "";
            var data = "";

            //document.getElementById('LightBoxC').innerHTML == "";
            //document.getElementById('LightBoxC').innerHTML = "<font color='black'  > &#0149; </font><a  class='thickbox' href='slide show/default2.aspx?abid=" + albumID + "&id=12&keepThis=true&TB_iframe=true&height=400&width=400' title='PhotoGallery' ><span > SlideShow</span></a>";
            $("#LightBoxC").css("display", "block");
            //tb_reload();
        }
    });

}


//get data when any picture is clicked in jcaroseul
function DisplayData(Link, description, cutline, byline, picID, val, uploaded) {
	
	stopEventBubbling();
    
    document.getElementById('picID').value = picID;
    FadeonClick(picID);
    
    //clearing the comment div and the comment inputbox
    document.getElementById('CommentDiv').innerHTML = "";
    document.getElementById('inputBox').value = "";
    
    var articleType = document.getElementById('articleID').value;
    var pgType = document.getElementById('pgType').value
    

    // If the page is community, pubType = 1, else pubType = 0
    var pubType = 0;
    var xslParameters = null;
    if (isCommunity()) {
        pubType = 1;
        xslParameters = new Array();
        xslParameters["community"] = "1";
        updateReportImageLink();
    } else {

    }


    $.ajax({
        //url of the webservice
        url: 'GetData.asmx/DisplayImgData',
        //parameters passes to the method

        data: "picID=" + picID + "&pgType=" + pgType + "&abID=" + albumID + "&arID=" + articleType + "&pub_type=" + pubType,
        type: 'GET',
        processData: false,
        //return type
        dataType: 'xmlDocument',
        //time afer which the webservice will time out
        timeout: 3000,
        //error handler
        error: function() {
            alert('Error loading XML document: DisplayData');
        },
        //success method
        success: function(xmlDocument) {
            //apply xsl to xml
            displayResult(xmlDocument, "CommentStyle.xsl", "CommentDiv", xslParameters);
            var msg = "";
            var data = "<center>";
            msgDiv = document.getElementById("msg");
            msgDiv.style.display = "none";
            msgDiv.innerHTML = "";


            var author = "<table width='100%' border='0px' style='padding-top:0px;'><tr><td valign='top' align='right' style='font-size:10px;'>";
            if (trim(byline) != "") {
                author += "Photo by: " + byline + "&nbsp;&nbsp;&nbsp;&#0149;&nbsp;&nbsp;&nbsp;";

            }
            if (uploaded != "") {
                author += "" + uploaded;
            }
            if (trim(description) != "") {
                author += "<tr><td valign='top' align='center' >" + description + "</td></tr>";
            }
            else if (trim(cutline) != "") {
                author += "<tr><td valign='top' align='center' >" + cutline + "</td></tr>";
            }
            author += "</table>";


            var imageField = document.getElementById('imageB');
            imageField.innerHTML = "<center><img src= '" + Link + "'/></center>" + author;
            
            ratingDiv = document.getElementById("RatingStarDiv");
            ratingDiv.style.display = "none";
            document.getElementById("StarContainerDiv").style.display = "block";
            document.getElementById("SubRating").style.display = "block";
            document.getElementById('picID').value = picID;
            
            EnableRating();
            getPicRatings();
            clearMainMsg();

            //document.getElementById('LightBoxC').innerHTML = "<font color='black'  > &#0149; </font><a class='thickbox' href='slide show/default2.aspx?abid=" + albumID + "&id=12&keepThis=true&TB_iframe=true&height=400&width=400' title='PhotoGallery' ><span > SlideShow</span></a>";
            $("#LightBoxC").css("display", "block");
            //tb_reload();
        }
    });
}


function LoadJcarosel(albumID) {
    $.ajax({
        url: 'GetData.asmx/JCaroselData',
        data: "albumID=" + albumID,
        type: 'GET',
        processData: false,
        dataType: 'xmlDocument',
        timeout: 3000,
        error: function() {
            alert('Error loading XML document: LoadJcarosel');
        },
        success: function(xmlDocument) {
            displayResult(xmlDocument, "/App_Data/XSLT/PhotoGallery/Gallery.xsl", "JCarosel", null);
        }
    });

}
function PostComment() {
    var imageID = document.getElementById('picID').value;
    var commentText = document.getElementById('inputBox').value;
    var articleID = document.getElementById('articleID').value;
    
    var pubType = 0;
    if (isCommunity())
        pubType = 1;


    $.ajax({
        url: 'GetData.asmx/storeComment',
        data: "_photo_ID=" + imageID + "&_sComments=" + commentText + "&_article_ID=" + articleID + "&_sUserID=" + userID + "&_sUserName=" + userName + "&_sIPaddress=" + ipAddInfo + "&pub_type=" + pubType,
        type: 'GET',
        processData: false,
        dataType: 'xmlDocument',
        timeout: 3000,
        error: function() {
            alert('Error loading XML document: PostComment');
        },
        success: function(xmlDocument) {

            getNodeValue(xmlDocument, "Comments", "");
        }
    });

}

function getinitialValues(xmlDocument, NodeVal) {

}

function getNodeValue(xmlDocument, NodeVal, contentType) {

    try //Internet Explorer
  {
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xmlDocument);
    }
    catch (e) {
        try //Firefox, Mozilla, Opera, etc.
  {
            parser = new DOMParser();
            xmlDoc = parser.parseFromString(xmlDocument, "text/xml");
        }
        catch (e) {
            alert(e.message);
            return;

        }

    }
    var reqdlogin = xmlDoc.getElementsByTagName("cCode")[0].childNodes[0].nodeValue//);
    if (reqdlogin == "true") {

        var session_flag = xmlDoc.getElementsByTagName("session_flag")[0].childNodes[0].nodeValue;
        var Item_ID = xmlDoc.getElementsByTagName("Item_ID")[0].childNodes[0].nodeValue;
        LoginPage(session_flag, Item_ID, NodeVal);
    }
    else {


        if (NodeVal == "Comments") {
            RefreshAfterPost(document.getElementById('picID').value);
            msgDiv = document.getElementById("msg");
            msgDiv.style.display = "block";
            msgDiv.innerHTML = "Your Comment has been saved";
        }
        else if (NodeVal == "Rating") {

            if (contentType == "1") {
                RefreshAfterPost(document.getElementById('picID').value);
                msgDiv = document.getElementById("msg");
                msgDiv.style.display = "block";
                msgDiv.innerHTML = "Your rating has been saved";
            }
            else if (contentType == "0") {
                getPicRatings();
                mainMsgDiv = document.getElementById("mainMsg");
                mainMsgDiv.innerHTML = "<div style='width:145px; float:left;height:auto;text-align:center;background-color:Gold;font-weight:bold;font-size:12px;color:Black;position:relative;left:4px;'>Rating Saved</div>";
                mainMsgDiv.style.display = "block";

            }
        }
    }
}

function refreshAfterReport() {
    RefreshAfterPost(document.getElementById('picID').value);
}

function refreshAfterImageReport(picID) {
    var pgID = (qsParm['pageID']);
    var pgType = document.getElementById('pgType').value
    var redirectAfterReport = '../PhotoGallery/PhotoGallery.aspx?abID=' + albumID + '&imgID=' + picID + '&pageID=' + pgID + '&page=' + pgType;
    if (isCommunity())
        redirectAfterReport += '&community=1';
    window.location = redirectAfterReport;
}

// Rollover for image Stars //
function ratingSys(num) {
    sMax = 0; // Isthe maximum number of stars
    for (n = 0; n < num.parentNode.childNodes.length; n++) {
        if (num.parentNode.childNodes[n].nodeName == "A") {
            sMax++;
        }
    }

    if (!rated) {
        s = num.id.replace("_", ''); // Get the selected star
        a = 0;
        for (i = 1; i <= sMax; i++) {
            if (i <= s) {
                document.getElementById("_" + i).className = "on";
                holder = a + 1;
                a++;
            } else {
                document.getElementById("_" + i).className = "";
            }
        }
    }
}

// For when you roll out of the the whole thing //
function off(me) {
    if (!rated) {
        if (!preSet) {
            for (i = 1; i <= sMax; i++) {
                document.getElementById("_" + i).className = "";
            }
        } else {
            ratingSys(preSet);
        }
    }
}

// When you actually rate something //
function rateIt(me) {
    if (!rated) {
        preSet = me;
        rated = 1;
        sendRate(me);
        ratingSys(me);
    }

}

// Send the rating information somewhere using Ajax or something like that.
function sendRate(sel) {

    var picID = document.getElementById('picID').value;

    rating(sel.title, picID, 0);

    ratingDiv = document.getElementById("RatingStarDiv");
    ratingDiv.style.display = "none";
    document.getElementById("StarContainerDiv").style.display = "block";
    document.getElementById("SubRating").style.display = "block";
}

function LoginPage(session_flag, Item_ID, Section) {

    var type = "";
    if (Section == "Rating") {
        type = "Rate";
    }
    else if (Section == "Comments") {
        type = "C1";
    }

    var pgType = qsParm['pageID'];


    var picID = document.getElementById('picID').value;

    var articleType = document.getElementById('articleID').value;
    var loginPageURL = "../Account/loginPage.aspx?cnt_id=" + Item_ID + "&ctype=" + type + "&cC=" + session_flag + "&t=" + type + "&i=" + Item_ID + "&ph_ID=" + picID + "&ar_ID=" + articleType + "&pgType=" + pgType + "&abID=" + albumID + "&createCode=true";
    if (isCommunity()) {
        loginPageURL += "&community=1";
    }
    location.href = loginPageURL;
}

function LoadQS() {
    var query = window.location.search.substring(1);
    var parms = query.split('&');
    for (var i = 0; i < parms.length; i++) {
        var pos = parms[i].indexOf('=');
        if (pos > 0) {
            var key = parms[i].substring(0, pos);
            var val = parms[i].substring(pos + 1);
            qsParm[key] = val;
        }
    }

}

function getFirstImageId() {
    var firstID = "";

    var imageID = document.getElementById("picID").value;
    var List = document.getElementById("ImageList").value;

    var SplitImageList = List.split(",");
    nextID = SplitImageList[0];

    return trim(nextID);

}
function getNextImageId() {
    var nextID = "";

    var imageID = document.getElementById("picID").value;
    var List = document.getElementById("ImageList").value;
    var SplitImageList = List.split(",");
    var i = 0;
    for (i = 0; i < SplitImageList.length; i++) {
        if (parseInt(SplitImageList[i]) == parseInt(imageID)) {
            if (i < (SplitImageList.length - 1)) {
                nextID = SplitImageList[i + 1]
                break;
            }
            else {
                nextID = SplitImageList[0];
            }
        }
    }
    return nextID;
}

function getPreviousImageId() {
    var PreviousID = "";

    var imageID = document.getElementById("picID").value;
    var List = document.getElementById("ImageList").value;
    var SplitImageList = List.split(",");
    var i = 0;
    for (i = 0; i < SplitImageList.length; i++) {
        if (parseInt(SplitImageList[i]) == parseInt(imageID)) {
            if (i > 0) {
                PreviousID = SplitImageList[i - 1]
                break;
            }
            else {
                PreviousID = SplitImageList[SplitImageList.length - 1]
            }

        }
    }
    return PreviousID;
}

function nextImage() {
	
	stopEventBubbling();
	
    var nextID = getNextImageId();
    var LoadImage = true;

    if (LoadImage) {
        document.getElementById('picID').value = nextID;
        OnNext(nextID);
    }
}

function previousImage() {
	
	stopEventBubbling();
	
    var PreviousID = getPreviousImageId();
    var LoadImage = true;

    if (LoadImage) {
        document.getElementById('picID').value = PreviousID;
        OnNext(PreviousID);
    }
}


function getCount() {

    var PreviousID = "";
    var imageID = document.getElementById("picID").value;
    var List = document.getElementById("ImageList").value;
    var SplitImageList = List.split(",");

    var counter = 0;
    var i = 0;

    for (i = 0; i < SplitImageList.length; i++) {

        if (parseInt(SplitImageList[i]) == parseInt(imageID)) {
            counter = i + 1;
            break;
        }
    }

    document.getElementById("imgCounter").innerHTML = counter + "/" + SplitImageList.length;


}

String.prototype.ltrim = function() {
    return this.replace(/^\s+/, "");
}
String.prototype.rtrim = function() {
    return this.replace(/\s+$/, "");
}


function ShowRateDiv() {
    ratingDiv = document.getElementById("RatingStarDiv");
    document.getElementById("StarContainerDiv").style.display = "none";
    document.getElementById("SubRating").style.display = "none";

    ratingDiv.style.display = "block";
    clearMainMsg();

}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));

        }
    }
    return "";
}

function AlbumPage() {
    var photoGalDisplayUrl = "PhotoGalDisplay.aspx";
    if (isCommunity())
        photoGalDisplayUrl += "?community=1";
    location.href = photoGalDisplayUrl;
}

function PreviousPage() {
    var pgID = qsParm['pageID'];
    if (pgID == "1") {
        var page = (qsParm['page']);

        location.href = "PhotoGalDisplay.aspx?page=" + page;
    }
    else if (pgID == "2") {
        var arID = (qsParm['arID']);
        location.href = "../ArticleDisplay.aspx?e" + arID;
    }
    else if (pgID == "3") {
        var arID = (qsParm['arID']);
        location.href = "/";
    }

}

function EnableRating() {
    rated = 0;
    preSet = 0;
    off(document.getElementById("_1"));
    off(document.getElementById("_2"));
    off(document.getElementById("_3"));
    off(document.getElementById("_4"));
    off(document.getElementById("_5"));
}

function getPicRatings() {
    var pictureID = document.getElementById('picID').value

    var pubType = 0;
    if (isCommunity())
        pubType = 1;

    $.ajax({
        url: 'GetData.asmx/getImageRatings',
        data: "imageID=" + pictureID + "&contentType=0" + "&pubType=" + pubType,
        type: 'GET',
        processData: false,
        dataType: 'xmlDocument',
        timeout: 3000,
        error: function() {
            alert('Error loading XML document: getPicRatings');
        },
        success: function(xmlDocument) {


            try //Internet Explorer
  {
                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async = "false";
                xmlDoc.loadXML(xmlDocument);
            }
            catch (e) {
                try //Firefox, Mozilla, Opera, etc.
  {
                    parser = new DOMParser();
                    xmlDoc = parser.parseFromString(xmlDocument, "text/xml");
                }
                catch (e) {
                    alert(e.message);
                    return;

                }

            }

            var Score_Count;
            var People_Count;

            try {
                Score_Count = xmlDoc.getElementsByTagName("Score_Count")[0].childNodes[0].nodeValue;
                People_Count = xmlDoc.getElementsByTagName("People_Count")[0].childNodes[0].nodeValue;
            }
            catch (e) {
                People_Count = "0";
                Score_Count = "0";

            }


            if (People_Count != "0") {
                avg = (parseInt(Score_Count) / (parseInt(People_Count) * 5)) * 100;
                avg = Math.round((avg / 100) * 70);
            }
            else {
                avg = "0";

            }
            refreshStarDiv = document.getElementById("starinner");

            refreshStarDiv.style.width = avg + "px";

        }
    });

}

function clearMainMsg() {
    mainMsgDiv = document.getElementById("mainMsg");
    mainMsgDiv.innerHTML = "";
    mainMsgDiv.style.display = "none";

}
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return ""
}

function setCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : "; expires=" + exdate.toGMTString());
}

function checkCookie(contentID, contentType) {

    if (contentType == 1) {
        CookieName = getCookie('thumbs');

    }
    else if (contentType == "0") {
        CookieName = getCookie('Picture');

    }
    if (CookieName != null && CookieName != "") {


        return CookieName;
    }
    else {
        if (contentType == 1) {
            Name = "thumbs";

        }
        else if (contentType == "0") {
            Name = "Picture";
        }
        setCookie(Name, contentID, 1);
        return "No";
    }

}


// Ranyodh Singh
// Funtion that determines if this page is a community page, using community=1 query string
function isCommunity() {
    if (parseInt(qsParm["community"]) == 1)
        return true;
    return false;
}

function updateReportImageLink() {

    var imgID = document.getElementById('picID').value;
    var arID = document.getElementById('articleID').value
    var pgType = document.getElementById('pgType').value;

    var nextImage = trim(getNextImageId());

    var linkHref = '/report/default.aspx?ctId=8&abId=' + albumID + '&thrId=' + imgID + '&imgId=' + imgID + '&arID=' + arID + '&PgType=' + pgType + '&community=1&nextImg=' + nextImage + '&keepThis=true&TB_iframe=true&height=400&width=400';

    $("#reportImageDiv").css("display", "block");
    document.getElementById('reportImageDiv').innerHTML = '';
    document.getElementById('reportImageDiv').innerHTML = '<a href="' + linkHref + '" id="reportImageLink" class="thickbox"  title="Report this Image"><span>Report Image</span></a>';
    tb_init('#reportImageLink');
}

function stopEventBubbling() {
	
	// For stoopping event bubbling in IE
	if(!e) var e = window.event;
	//e.cancelBubble is supported by IE - this will kill the bubbling process.
	if(e) {
		e.cancelBubble = true;
		e.returnValue = false;
	}
	//
}
