function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function ClearInput(value, id){
	var input = document.getElementById(id);
	if(value == input.value){
		input.value = '';
	}
	else{
		input.value = input.value;
	}
}

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }
String.prototype.startsWith = function(str) { return (this.match("^" + str) == str); }
function isValidEmail(email) {
    var regex = /([\w\d\-_]+)(\.[\w\d\-_]+)*@([\w\d\-_]+\.)([\w\d\-_]+\.)*([\w]{2,3})/;

    if (regex.test(email))
        return true;
    else
        return false;
}
function resetText(obj, text, isClick) {
    if (obj.val() == text && isClick)
        obj.val('');
    else if (obj.val() == '' && !isClick)
        obj.val(text);
}
/*start blog*/
$(document).ready(function() {

    //Set top banner to display
    $('.aGigyaShare').click(function() {
        showShareUI('multiSelect');
    });

    $('.blog-reply').click(function() {
        $(this).next('.blog-reply-comment').html(
        '<div class="form replyForm"><div class="clearer high16">&nbsp;</div><h3>Reply</h3><div class="clearer"></div><p class="blog-reply-error"></p><input name="tbBlogCommentName" class="inputText" value="Your Name" type="text"><div class="clearer"></div><input name="tbBlogCommentEmail" class="inputText" value="Your Email [not displayed on the website]" type="text"><div class="clearer"></div><textarea name="tbBlogCommentComment" cols="20" rows="2" value="Your Comment">Your Comment</textarea><div class="clearer"></div><a href="javascript:void(0)" class="orangeButton repyButton"><span>SUBMIT</span></a><a href="javascript:void(0)" class="orangeButton blog-reply-cancel"><span>CANCEL</span></a><div class="clearer">&nbsp;</div></div>');
        $('.blog-reply-cancel').click(function() {
            $(this).parents('.blog-reply-comment').html('');
        });
        $('input[name=tbBlogCommentName]').click(function() {
            resetText($(this), 'Your Name', true);
        });
        $('input[name=tbBlogCommentName]').blur(function() {
            resetText($(this), 'Your Name', false);
        });
        $('input[name=tbBlogCommentEmail]').click(function() {
            resetText($(this), 'Your Email [not displayed on the website]', true);
        });
        $('input[name=tbBlogCommentEmail]').blur(function() {
            resetText($(this), 'Your Email [not displayed on the website]', false);
        });
        $('textarea[name=tbBlogCommentComment]').click(function() {
            resetText($(this), 'Your Comment', true);
        });
        $('textarea[name=tbBlogCommentComment]').blur(function() {
            resetText($(this), 'Your Comment', false);
        });
        $('.repyButton').click(function() {
            var name = $(this).siblings('input[name=tbBlogCommentName]').val();
            var email = $(this).siblings('input[name=tbBlogCommentEmail]').val();
            var comment = $(this).siblings('textarea[name=tbBlogCommentComment]').val();
            var root = $('#blogRootId').val();

            //validation
            $(this).siblings('p.blog-reply-error').html('');
            var isValid = true;
            var errorMsg = '';
            if (name.trim() == '' || name.trim().toLowerCase() == 'your name') {
                isValid = false;
                errorMsg += 'Please enter your name<br />';
            }
            if (email.trim() == '' || email.trim().toLowerCase() == 'your email [not displayed on the website]') {
                isValid = false;
                errorMsg += 'Please enter your email address<br />';
            }
            else if (!isValidEmail(email)) {
                isValid = false;
                errorMsg += 'Please enter a valid email address<br />';
            }
            if (comment.trim() == '' || comment.trim().toLowerCase() == 'your comment') {
                isValid = false;
                errorMsg += 'Please enter your comment<br />';
            }
            if (!isValid) {
                $(this).siblings('p.blog-reply-error').html(errorMsg);
                return false;
            }

            var commentID = $(this).parents('.comment').children('input:hidden').val();
            $(this).html('Submitting... Please Wait');
            jQuery.post('/handlers/BlogCommentReply.ashx', { commentid: commentID, name: name, email: email, comment: comment, root: root }, function(data) {
                var result = data;
                if (data.startsWith('Success')) {
                    if (data.startsWith("Success:posted")) {
                        $('#divBlogReplyComment-' + commentID).html('<p>Your reply has been posted.</p>');
                        var newCommentHTML = $('#ulBlogCommentReply-' + commentID).html() + '<li>' + comment + '<br /><cite>' + name + '</cite><small class="commentmetadata">' + data.split(':')[2] + '</small</li>';
                        $('#ulBlogCommentReply-' + commentID).html(newCommentHTML);
                    }
                    else {
                        $('#divBlogReplyComment-' + commentID).html('<p>Your reply is now submitted and pending approval.</p>');
                    }
                }
                else {
                    $('#divBlogReplyComment-' + commentID).html('An error had occurred. Please try again later.');
                }
            });
        });
    });
});
/*end blog*/

function showLogin() {
    $('#loginContainer').show('fast');
    $('#loginLink').hide();
    $('#closeLink').show();
}

function hideLogin() {
    $('#loginContainer').hide('fast');
    $('#closeLink').hide();
    $('#loginLink').show();
}

function initSecureLinks() {
    $('.secureLink').click(function() {
        showLBMain('lightBox2');
        //set url to go
        $('#GoURL').attr("value", this);
        window.location = '#top';
        return false;
    });
}
function updateCommentStream(start, end) {
    $.get('commentfeed.aspx?start=' + start + "&end=" + end, function(data) {
        $('.commentStream').html(data);
    });
}


var slidingGalleryPause = false;
var slidingGallery = {
    galleryObj: null,
    images: null,
    count: null,
    itemWidth: null,
    index: 0,
    reverse: false,
    invertedIt: false,
    interval: 4000,
    timing: 500,
    timer: null,
    currentlyanimating: false,
    initialize: function(obj, rev, inta) {
        slidingGallery.galleryObj = obj;
        slidingGallery.images = obj.find("a.item");
        slidingGallery.count = slidingGallery.images.length;
        slidingGallery.itemWidth = $(slidingGallery.images[0]).innerWidth();
        if (rev) {
            slidingGallery.reverse = true;
        }
        if (inta) {
            slidingGallery.interval = inta;
        }
        slidingGallery.timer = setInterval(slidingGallery.step, slidingGallery.interval);
    },
    step: function() {

        if (slidingGalleryPause) {
            slidingGalleryPause = false;
            return;
        }
        var offset = 0;
        if (slidingGallery.reverse) {
            var el = slidingGallery.galleryObj.find("a.item:last");
            slidingGallery.galleryObj.find("a.item:last").remove();
            slidingGallery.galleryObj.prepend('<a class="item" target="' + el.attr('target') + '" href="' + el.attr('href') + '">' + el.html() + '</a>');
            slidingGallery.galleryObj.css("margin-left", "-" + slidingGallery.itemWidth + "px");
        }
        else {
            offset = 0 - slidingGallery.itemWidth;
        }
        slidingGallery.galleryObj.stop().animate({
            marginLeft: offset + "px"
        },
            slidingGallery.timing,
            function() {

                if (!slidingGallery.reverse) {
                    var el = slidingGallery.galleryObj.find("a.item:first");
                    slidingGallery.galleryObj.find("a.item:first").remove();
                    slidingGallery.galleryObj.css("margin-left", 0);
                    slidingGallery.galleryObj.append('<a class="item" target="' + el.attr('target') + '" href="' + el.attr('href') + '">' + el.html() + '</a>');
                }
                if (slidingGallery.invertedIt) {
                    slidingGallery.reverse = !slidingGallery.reverse;
                    slidingGallery.invertedIt = false;
                }
                slidingGallery.currentlyanimating = false;
            });
        if (!slidingGallery.timer) {
            slidingGallery.timer = setInterval(slidingGallery.step, slidingGallery.interval);
        }

    },
    stepForward: function() {
        if (!slidingGallery.currentlyanimating) {
            slidingGallery.currentlyanimating = true;
            clearInterval(slidingGallery.timer);
            slidingGallery.timer = null;
            slidingGalleryPause = false;
            slidingGallery.step();
            clearInterval(slidingGallery.timer);
            slidingGalleryPause = true;
            
        }
        return false;
    },
    stepBackwards: function() {
        
        if (!slidingGallery.currentlyanimating) {

            slidingGallery.currentlyanimating = true;
            clearInterval(slidingGallery.timer);
            slidingGallery.timer = null;
            slidingGallery.reverse = !slidingGallery.reverse;
            slidingGallery.invertedIt = true;
            slidingGalleryPause = false;
            slidingGallery.step();
            clearInterval(slidingGallery.timer);
            slidingGalleryPause = true;
            
        }
        return false;
    }
}
/*gigya*/
// Create and Publish User's Action
// This method is associated with the "btnPublishAction" click
/*function showShareUI(operationMode) {
    var act = new gigya.services.socialize.UserAction();
    act.setUserMessage('Your comment here...');
    var share_params =
        {
            userAction: act
	        , showEmailButton: true
	        , showMoreButton: true
	        , enabledProviders: 'facebook, twitter, stumbleupon, reddit, digg, linkedin'
        }
    gigya.services.socialize.showShareUI(conf, share_params);
}*/
function showShareUI(operationMode) {    
    // Constructing a UserAction Object
    var act = new gigya.services.socialize.UserAction();

    // Setting the default user message 
    // (will be presented as default text in the edit box on the Share UI)
    act.setUserMessage("Your comment here...");

    // Setting the title and description 
    // (will be presented in the preview on the Share UI)
    act.setTitle($('.middleColHeader h2').html());
    act.setDescription($('.middleColHeader .hiddenSynopsis').html());

    // Setting a link back to the publishing source
    act.setLinkBack(document.location.href + '?h=' + $('.PageNodeHash').html());
    
    /*// Adding Action Link
    act.addActionLink("Watch the movie",
		        "http://www.youtube.com/watch?v=jqxENMKaeCU&feature=channel_page");

    // Adding a video (will be presented in the preview on the Share UI)
    var video = {
        src: 'http://www.youtube.com/watch?v=G8IozVfph7I&feature=channel_page',
        previewImageURL: 'http://i4.ytimg.com/vi/G8IozVfph7I/default.jpg',
        type: 'flash'
    }
    act.addMediaItem(video);*/

    // Parameters for the showShareUI method, including the UserAction object
    var params =
			{
			    userAction: act  // The UserAction object enfolding the newsfeed data.	
				, operationMode: operationMode// Opens the Share Plugin either in Simple or Multiselect mode according to the user connection status. 
			    , snapToElementID: "btnShare" // Snaps the Simple Share Plugin to the share button
				, onError: onError  // onError method will be summoned if an error occurs. 
			    , onSendDone: onSendDone // onError method will be summoned after 
			    // Gigya finishes the publishing process.
				, context: operationMode
				, showMoreButton: true // Enable the "More" button and screen
				, showEmailButton: true // Enable the "Email" button and screen
                , enabledProviders: "facebook, twitter, linkedin, yahoo, messenger, myspace"
                , moreEnabledProviders: "digg, stumbleupon, reddit, delicious, friendfeed, googlebuzz, googlebookmarks, messenger, myaol, livebookmarks, technorati, plaxo, slashdot, Tumblr, faves, newsvine, fark, mixx, Bit.ly, misterwong, ask, amazon, gmail, baidu, box.net, netlog, evernote, aolmail, propeller, currenttv, simpy, yardbarker, blinklist, diigo, sphinn, backflip, dropjack, segnalo, linkagogo, kaboodle, skimbit, Hyves, facebookshare, twitter, yahoobookmarks, linkedin"
			};

    // Show the "Share" dialog
    gigya.services.socialize.showShareUI(conf, params);

}

// onError event handler
function onError(event) {
    alert('An error has occured' + ': ' + event.errorCode + '; ' + event.errorMessage);
}

// onSendDone event handler. 
// Displays in the status field, the list of providers to which the newsfeed has been 
// successfully published.
function onSendDone(event) {
    $.post("/handlers/Stats.ashx", { nodeid: $('.PageNodeHash').html() }, function(data) {

    });
    
    document.getElementById('status').style.color = "green";
    switch (event.context) {
        case 'multiSelect':
            document.getElementById('status').innerHTML = 'The newsfeed has been posted to: ' + event.providers;
            break;
        case 'simpleShare':
            document.getElementById('status').innerHTML = 'Clicked ' + event.providers;
            break;
        default:
            document.getElementById('status').innerHTML = 'Share onSendDone';
    }
}
