/* $Id$ */
function sanitizeURL(s)
{
	if(!s || s == '')
	{
		return s;
	}
	var pos = s.indexOf(":");
	if(pos != -1)
	{
		var st = s.substr(0,pos);
		if((st != ("http")) && (st != ("https"))  && (st != ("ftp")) && (st != "mailto"))
			s = "http://"+s;
	}
	else
	{
		s = "http://"+s;
	}
	return s;
}//sanitizeURL

function sanitize(s)
{
	if(s == null || s == '')
	{
            return s;
	}
	s = s.replace(/<!--(.|\n)*?-->/mg, "");
	s = s.replace(/<(title|script|style|meta|link)\b((.|\n)*?)<\/\1\b(.*?)>/gmi,"");
	s = s.replace(/<(title|script|style|meta|link)\b((.|\n)*?)>/gmi,"");
	s = s.replace(/<\/?(html|head|(x?meta)|title|script|style|link|noembed|bgsound|frame|frameset|noframes)((.|\n)*?)>\n*?/gmi,"");
	s = s.replace(/<\/?([a-z].*)\b[^>]*>/gmi,function(_1){
		_1=_1.replace(/\\0/gmi,'');
		_1=_1.replace(/<\/?body/gmi,function(_5){if(_5.toLowerCase() == '<body'){_5='<div';}else{_5="</div";}return _5;});
		_1=_1.replace(/\/\*[^*]+\*\//gmi,'');
		_1=_1.replace(/\Won[A-Z]*(\\s)*?=(\\s)*?(\'|\"|`)(.|\n)*?(\3)/gmi,'');
		_1=_1.replace(/\Wclass(\\s)*?=(\\s)*?(\'|\"|`)(.|\n)*?(\3)/gmi,'');
		_1=_1.replace(/\Wid(\\s)*?=(\\s)*?(\'|\"|`)(.|\n)*?(\3)/gmi,'');
		_1=_1.replace(/\Wdocument\.cookie/gmi,'');
		_1=_1.replace(/\.cookie/gmi,'');
		_1=_1.replace(/\Wwindow\.location/gmi,'');
		_1=_1.replace(/\.location/gmi,'');
		_1=_1.replace(/\Wjavascript(\\s|\n)*?:/gmi,'');
		_1=_1.replace(/(href|src)(\\s|\n)*?=(\\s|\n)*?(\'|\"|`)((.|\n)*?)[^\\](\4)/gmi,function(_2){
				var sub = _2.substr(0,3).toLowerCase();
				var htp=null;
				if(sub == 'hre'){
					htp = new RegExp("(\'|\"|`)((https?|ftp)|(mailto)):","gmi");
				}else if(sub == 'src'){
					htp = new RegExp("(\'|\"|`)(https?):|(^\/GetImage\?imageName=)","gmi");
				}
				_2=_2.replace(/(\'|\"|`)((.|\n)*?)[^\\](\1)/gmi,function(_3){
						if(!htp.test(_3)){
							_3="\"\"";
						}
						return _3;
						});
				return _2;
				});
		_1=_1.replace(/style(\\s|\n)*?=(\\s|\n)*?(\'|\"|`)((.|\n)*?)[^\\](\3)/gmi,function(_4){
				_4 = _4.replace(/url\((.|\n)*?\)/gmi,"");
				_4 = _4.replace(/expression\((.|\n)*?\)/gmi,"");
				return _4;
			});
		return _1;});
	s = s.replace(/<[a-z][a-z0-9]*\s?:\s?[a-z][a-z0-9]*[^>]*>/gmi,"");
	s = s.replace(/\s*?\n$/gmi,"");
	if(s.length > 40000)
	{
		alert(i18n['zohodiscussions.general.textExceedMaximumSizeMessage']);
		s=s.substring(0,40000);
	}
	return s;
}//function sanitize(s)

function validate($containerToValidate)
{
    //TODO: move this to a utils.js
    var $elementsToValidate = $(':input', $containerToValidate);
    var returnValue = true;

    //define default validation patterns and standard messages.
    var integer_pattern = /^[\-|\+]?\d+$/;
    var integer_message = 'Please enter a valid integer number';
    var float_pattern = /^[\-|\+]?(?:\d*\.?\d+|\d+\.)$/;
    var float_message = 'Please enter a valid number';
    var email_pattern = /^[a-zA-Z0-9]([\w\-\.\+]*)@([\w\-\.]*)(\.[a-zA-Z]{2,4}(\.[a-zA-Z]{2}){0,2})$/i;
    var email_message = 'Please enter a valid email';
    var multipleemail_pattern = /^(?:[a-zA-Z0-9]([\w\-\.\+]*)@([\w\-\.]*)(\.[a-zA-Z]{2,4}(\.[a-zA-Z]{2}){0,2}),?\s*)+$/i;
    var multipleemail_message = 'Please enter a valid email ids';
    var id_pattern = /^([\w-]+(?:[\w-]+)*)$/i;
    var id_message = 'Please enter a valid id. Spaces are not allowed';
    var url_pattern = /^(?:(?:\w|\d)+\.)+[a-zA-Z0-9]{2,6}$/;
    var url_message = 'Please enter a valid URL';
    var pattern_message = 'Sorry. The entered value does not match the required pattern';
    //start the validation process.
    $elementsToValidate
        .filter('[trim="true"]').each(function(index, eachItem)
        {	//remove all spaces from fields that are marked as trim
                $(eachItem).val($(eachItem).val().replace(/^\s+/, '').replace(/\s+$/,''));
        })//.filter('[trim="true"]').each(function(index, eachItem)
        .end() //remove the previous filter
        .filter('[mandatory="true"]').each(function(index, eachItem)
        {
                var $eachItem = $(eachItem);
                //Check if the mandatory fields have a value
                if($eachItem.val() == "")
                {
                        message = getCustomMessage ($eachItem, $eachItem.attr('title') + " cannot be left blank! Please provide a value");
                        showError ($eachItem,message);
                        returnValue = false;
                }//if($eachItem.val() == "")
        })//$elementsToValidate.filter('[mandatory="true"]').each()
        .end() 
        .filter('[dataType]').each(function(index, eachItem)
        {
            var $eachItem = $(eachItem);
            var valueToValidate = $eachItem.val();
            if(valueToValidate && valueToValidate != '')
            {
                var dataType = $eachItem.attr('dataType');
                try
                {
                    dataType = dataType.toLowerCase();
                    var patternToCheck = eval(dataType + '_pattern');

                    var defaultMessage = eval(dataType + '_message');
                    if (valueToValidate.match(patternToCheck) == null)
                    {
                        showError ($eachItem, getCustomMessage($eachItem, defaultMessage));
                        returnValue = false;
                    }//if ($eachItem.val().match(patternToCheck) == null)
                }catch(e){return;}
            }//if(valueToValidate != '')

        })
        .end() 
        .filter('[pattern]').each(function(index, eachItem)
        {
            //validate for a specified pattern
            var $eachItem = $(eachItem);
            var valueToValidate = $eachItem.val();
            if(valueToValidate && valueToValidate != '')
            {
                var patternToCheck = eval($eachItem.attr('pattern'));
                var defaultMessage = eval ('pattern_message');
                if (valueToValidate.match(patternToCheck) == null)
                {
                    showError (getCustomMessage($eachItem, defaultMessage));
                    returnValue = false;
                }
            }//if(valueToValidate != '')
        });//.filter('[pattern]').each(function(index, eachItem)
    return returnValue;
}//function validate($containerToValidate)

function getCustomMessage ($field, defaultMessage)
{
    try
    {
        ////TODO: move this to a utils.js
        customMessage = $field.attr('message');
        if (!customMessage || customMessage == "") {customMessage = defaultMessage;}
        return customMessage;
    }
    catch(e)
    {
        return defaultMessage;
    }
}

function showError($field,message)
{
    var errorLocation = $field.attr("name")+"_Error";
    //alert($('#'+errorLocation).length)
    $('#'+errorLocation).html(message).show();
    return false;
}//function showError()

function doAjaxAction(actionURL,options,callbackSuccessFunction,callbackErrorFunction)
{
    $.ajax(
    {
        url: actionURL,
        type: "POST",
        data: options,
        error: callbackErrorFunction,
        success : callbackSuccessFunction
    });
}
/***Method to show loading image***/
function showLoadingImage(loadingMessage)
{
    loadingMessage = loadingMessage || i18n['zohodiscussions.general.loading']+'...';
    $('#loadingText').html(loadingMessage);
    $('#loadingImg').show();
}
function hideLoadingImage()
{
    $('#loadingImg:visible').hide();
    $('#ajaxLoaderSmall').remove();
}

function showSmallLoadingImage(event,topOffset,leftOffset)
{
    topOffset = (topOffset != undefined)?topOffset:20;
    leftOffset = (leftOffset != undefined)?leftOffset:0;
    //to show small loading image
    var currPos = {};
    currPos.top = event.pageY-topOffset;
    currPos.left = event.pageX-leftOffset;
    var $loadingImageCont = $('#ajaxLoaderSmallTemp').clone();
    $loadingImageCont.attr('popoutPurpose','ajaxLoaderSmall');
    $loadingImageCont.attr('id','ajaxLoaderSmall');
    $loadingImageCont.css(currPos).show();
    $loadingImageCont.appendTo('body');
    $loadingImageCont.siblings('div[popoutPurpose="ajaxLoaderSmall"]').remove();
}

function showSmallLoadingImageForCont($target,topOffset,leftOffset)
{
    topOffset = (topOffset != undefined)?topOffset:0;
    topOffset = $target.offset().top+topOffset;
    leftOffset = (leftOffset != undefined)?leftOffset:0;
    leftOffset = $target.offset().left+leftOffset;

    var currPos = {};
    currPos.top = topOffset;
    currPos.left = leftOffset;
    var $loadingImageCont = $('#ajaxLoaderSmallTemp').clone();
    $loadingImageCont.attr('popoutPurpose','ajaxLoaderSmall');
    $loadingImageCont.attr('id','ajaxLoaderSmall');
    $loadingImageCont.css(currPos).show();
    $loadingImageCont.appendTo('body');
    $loadingImageCont.siblings('div[popoutPurpose="ajaxLoaderSmall"]').remove();
}
function goToTop(smoothScroll)
{
    if(smoothScroll && smoothScroll == true)
    {
        $('html,body').animate({scrollTop: 0}, 1000);
    }
    else
    {
         $(window).scrollTop(0);
    }
    return false;
}

//method to set focus to a container
function setFocusToContainer($container,smoothScroll,timeOut,topPx)
{
    var topDiff = $container.offset().top;
    var topShowPx = 50;
    if(topPx != undefined)
    {
        topShowPx = topPx;
    }
    if(smoothScroll && smoothScroll == true)
    {
        timeOut = timeOut || 1000;
        $('html,body').animate({scrollTop: topDiff-topShowPx},timeOut);
    }
    else
    {
        timeOut = (timeOut != undefined)?timeOut:300;
        if(timeOut > 0)
        {
            setTimeout(function(){$(window).scrollTop(topDiff-topShowPx);},timeOut);
        }
        else
        {
            $(window).scrollTop(topDiff-topShowPx);
        }
    }
    return false;
}

//method to show message container
function showMessage(message,messageType)
{
    messageType = messageType || "info";
    $('#messageContentCont').html(message);
    $('#messageContainer').attr('class',messageType).fadeIn(100,function(){setTimeout(function(){$('#messageContainer:visible').fadeOut(500)},6000)});
    $('#messageContainerClose').show();
    return false;
}
function hideMessage()
{
    $('#messageContainer').fadeOut(100);
}
//method to show tipper message
function showTipper(message,messageType,timeOut)
{
    messageType = messageType || "info";
    timeOut = timeOut || 4000;
    $('#messageContentCont').html(message);
    $('#messageContainerClose').hide();
    $('#messageContainer').attr('class',messageType).fadeIn(500,function(){setTimeout(function(){$('#messageContainer').fadeOut(500)},timeOut)});
}


function setToHotkeys()
{   
    if($('#topicListMainContainer').is(':visible'))
    {   
        setupKbdShortcuts();
    }
     
}//function setToHotkeys()

function setHotkeysToSinglePost()
{
    if($('#SinglePostContainer').is(':visible'))
    {
        setupKbdShortcutsToSinglePost();
    }
}

function removeHotkeys()
{
    $.hotkeys.remove('o');$.hotkeys.remove('esc');$.hotkeys.remove('j');$.hotkeys.remove('return');
    $.hotkeys.remove('space');$.hotkeys.remove('k');$.hotkeys.remove('shift+space');
    $.hotkeys.remove('n');$.hotkeys.remove('p');$.hotkeys.remove('v');
}//function removeHotkeys()

function findCurrentSinglePost()
{
	$currentSelected = $('#topicList').data('currentFocusPost');
        
        if(!$currentSelected || $currentSelected.length < 1)
        {   
            $currentSelected = $('#topicList').data('currentSelectedPost');
        }
	if(!$currentSelected || $currentSelected.length < 1)
	{
		$currentSelected = $('#topicList').find('div.singleTopicCont:first');
	}
	return $currentSelected;

}//function findCurrentSinglePost()

function setupKbdShortcuts()
{   
    $.hotkeys.add('',{disableInInput: true});
    $.hotkeys.add('o', function()
    { 
        var $currSelectedPost = findCurrentSinglePost();
        var currTopicId = $currSelectedPost.attr('forumTopicId');
        handleTopicClick($('quickView_'+currTopicId),currTopicId,"topicList"); 
    });//$.hotkeys.add('o', function()
    $.hotkeys.add('v', function()
    {
        var $currSelectedPost = findCurrentSinglePost();
        var currTopicId = $currSelectedPost.attr('forumTopicId');
        showLoadingImage();
        processHash('Topic/'+currTopicId);
    });//$.hotkeys.add('enter', function()
    $.hotkeys.add('esc', function()
    {
        var $currSelectedPost = findCurrentSinglePost();
        var currTopicId = $currSelectedPost.attr('forumTopicId');
        if($('#lastResponse_'+currTopicId).is(':visible'))
        {
            handleTopicClick($('quickView_'+currTopicId),currTopicId,"topicList");
        }    
    });//$.hotkeys.add('esc', function()
    $.hotkeys.add('return', function()
    {
        var $currSelectedPost = findCurrentSinglePost();
        var currTopicId = $currSelectedPost.attr('forumTopicId');
        window.open(serverURL+"?ftid="+currTopicId);
    });//$.hotkeys.add('return', function()
    $.hotkeys.add('space', function()
    {
        var $currentSelected = findCurrentSinglePost();

        //check if there is atleast one open post.
        if( $currentSelected.is('div.singleTopicContSel') )
        {
            //current selected is the currently opened post.
            var topicListTop = $(window).height();
            var scrollTop = $(window).scrollTop();
            var currPostHeight = $currentSelected.height();
            var nextpostTop = $currentSelected.next().offset().top;
            var isNextPostInView = ( topicListTop+scrollTop > nextpostTop );
            if(isNextPostInView)
            {   
                //next post is in view, so open the next post.
                $currentSelected = $currentSelected.next();
                if($currentSelected.is('.singleTopicCont'))
                {
                    var currTopicId = $currentSelected.attr('forumTopicId');
                    handleTopicClick($('quickView_'+currTopicId),currTopicId,"topicList"); 
                }    
            }//if(isNextPostInView)
            else
            {
                //next post is not in view, just scroll the page
                $(window).scrollTop(scrollTop + topicListTop - 50);
            }//else - if(isNextPostInView)
        }
        else
        {
            //current selected is possibly the first post, so it is not open, space should just open it.
            if($currentSelected.is('.singleTopicCont'))
            {
               var currTopicId = $currentSelected.attr('forumTopicId');
               handleTopicClick($('quickView_'+currTopicId),currTopicId,"topicList"); 
            }   
        }
    });//$.hotkeys.add('space', function()
    $.hotkeys.add('shift+space', function()
    {
        var $currentSelected = findCurrentSinglePost();
        //check if there is atleast one open post.
        if( $currentSelected.is('div.singleTopicContSel') )
        {
            //current selected is the currently opened post.
            var topicListTop = $(window).height();
            var scrollTop = $(window).scrollTop();
            var prevPostTop = $currentSelected.prev().offset().top;
            
            var isPrevPostInView = (scrollTop-topicListTop < prevPostTop-50);
            if(isPrevPostInView)
            {
                $currentSelected = $currentSelected.prev();
                if($currentSelected.is('.singleTopicCont'))
                {
                    var currTopicId = $currentSelected.attr('forumTopicId');
                    handleTopicClick($('quickView_'+currTopicId),currTopicId,"topicList"); 
                }
            }//if(isPrevPostInView)
            else
            {
                //prev post is not in view, just scroll up the page
                $(window).scrollTop((scrollTop - topicListTop) + 50);
            }//else - if(isPrevPostInView)
        }
        else
        {
            if($currentSelected.is('.singleTopicCont'))
            {
               var currTopicId = $currentSelected.attr('forumTopicId');
               handleTopicClick($('quickView_'+currTopicId),currTopicId,"topicList"); 
            } 
        }
    });//$.hotkeys.add('shift+space', function()
    $.hotkeys.add('j', function()
    {
        var $currentSelected = findCurrentSinglePost();
        if($currentSelected.is('div.singleTopicContSel'))
        {
            $currentSelected = $currentSelected.next();
        }
        if($currentSelected.is('div.singleTopicCont'))
        {
            var currTopicId = $currentSelected.attr('forumTopicId');
            handleTopicClick($('quickView_'+currTopicId),currTopicId,"topicList");
        }    
    });//$.hotkeys.add('j', function()
    $.hotkeys.add('k', function()
    {
        var $currentSelected = findCurrentSinglePost();
        if($currentSelected.is('div.singleTopicContSel'))
        {
            $currentSelected = $currentSelected.prev();
        }
        if($currentSelected.is('div.singleTopicCont'))
        {
            var currTopicId = $currentSelected.attr('forumTopicId');
            handleTopicClick($('quickView_'+currTopicId),currTopicId,"topicList");
        }    
    });//$.hotkeys.add('k', function()
    $.hotkeys.add('n', function()
    {
        var $currentSelected = findCurrentSinglePost();
        var $nextFromCurrSelected = $currentSelected.next();
        if($nextFromCurrSelected.is('div.singleTopicCont') || $nextFromCurrSelected.is('div.singleTopicContSel'))
        {   
            $currentSelected.removeClass('hotKeyTopicCont');
            $nextFromCurrSelected.addClass('hotKeyTopicCont');
            $('#topicList').data('currentFocusPost',$nextFromCurrSelected);
            toSetFocusOnCurrPost($nextFromCurrSelected,"next");
        }    
    });
    $.hotkeys.add('p', function()
    {    
        var $currentSelected = findCurrentSinglePost();
        var $prevFromCurrSelected = $currentSelected.prev();
        if($prevFromCurrSelected.is('div.singleTopicCont') || $prevFromCurrSelected.is('div.singleTopicContSel'))
        {   
            $currentSelected.removeClass('hotKeyTopicCont');
            $prevFromCurrSelected.addClass('hotKeyTopicCont');
            $('#topicList').data('currentFocusPost',$prevFromCurrSelected);
            toSetFocusOnCurrPost($prevFromCurrSelected,"prev");
        }
     });    
}//function setupKbdShortcuts()

function toSetFocusOnCurrPost($currentSelected,isProvide)
{
    var focusPostTop = $currentSelected.offset().top;
    var windowHeight = $(window).height();
    var scrollTop = $(window).scrollTop();
    if(isProvide == "next")
    {
        if(focusPostTop-scrollTop > windowHeight-50)
        {
            $(window).scrollTop((focusPostTop-windowHeight)+80);
        }
    }
    else
    {
        if(scrollTop > focusPostTop)
        {
           $(window).scrollTop(focusPostTop);
        }

    }
}

function setupKbdShortcutsToSinglePost()
{
    $.hotkeys.add('',{disableInInput: true});
    $.hotkeys.add('o', function()
    { 
        return false;
    });//$.hotkeys.add('o', function()
    $.hotkeys.add('v', function()
    {
        return false;
    });//$.hotkeys.add('enter', function()
    $.hotkeys.add('esc', function()
    {
        return false;  
    });//$.hotkeys.add('esc', function()
    $.hotkeys.add('return', function()
    {
        var currTopicId = $('#SinglePostContainer').attr('forumTopicId');
        window.open(serverURL+"?ftid="+currTopicId);
    });//$.hotkeys.add('return', function()
    $.hotkeys.add('space', function()
    {
        var topicListTop = $(window).height();
        var scrollTop = $(window).scrollTop();
        $(window).scrollTop(scrollTop+topicListTop);    
    });//$.hotkeys.add('space', function()
    $.hotkeys.add('shift+space', function()
    {
        var topicListTop = $(window).height();
        var scrollTop = $(window).scrollTop();
        $(window).scrollTop(scrollTop-topicListTop);   
    });//$.hotkeys.add('shift+space', function()
    $.hotkeys.add('j', function()
    {
        $currentSelected = findCurrentSingleResponse();
        var keyCount = 0;
        var currKey = $currentSelected.attr('currkey');
        if(currKey != undefined)
        {
            keyCount = currKey;
        }
        keyCount++;
        toSetFocusOnCurrResponse($currentSelected,keyCount);
    });//$.hotkeys.add('j', function()
    $.hotkeys.add('k', function()
    {
        $currentSelected = findCurrentSingleResponse();
        var keyCount = 0;
        var currKey = $currentSelected.attr('currkey');
        if(currKey != undefined)
        {
            keyCount = currKey;
        }
        else
        {
            return false;
        }
        keyCount--;
        toSetFocusOnCurrResponse($currentSelected,keyCount);  
    });//$.hotkeys.add('k', function()
    $.hotkeys.add('n', function()
    {   
        $currentSelected = findCurrentSingleResponse();
        var keyCount = 0;
        var currKey = $currentSelected.attr('currkey');
        if(currKey != undefined)
        {
            keyCount = currKey;
        }
        keyCount++;
        toSetFocusOnCurrResponse($currentSelected,keyCount);
    });
    $.hotkeys.add('p', function()
    {   
        $currentSelected = findCurrentSingleResponse();
        var keyCount = 0;
        var currKey = $currentSelected.attr('currkey');
        if(currKey != undefined)
        {
            keyCount = currKey;
        }
        else
        {
            return false;
        }
        keyCount--;
        toSetFocusOnCurrResponse($currentSelected,keyCount);
    });

}//function setupKbdShortcutsToSinglePost()

function findCurrentSingleResponse()
{
    $currentSelected = $('#SinglePostContainer').data('currentFocusResponse');
    if(!$currentSelected || $currentSelected.length < 1)
    {
            var currForumTopicId = $('#SinglePostContainer').attr('forumTopicId');
            $currentSelected = $('#SinglePostContainer_'+currForumTopicId).find('div.postContainer');
    }
    return $currentSelected;

}//function findCurrentSingleResponse()

function toSetFocusOnCurrResponse($currentSelected,keyCount)
{
    
    var currForumTopicId = $('#SinglePostContainer').attr('forumTopicId');
     var $focusResponse = "";

    if(keyCount == "0" )
    {
       $focusResponse =  $('#SinglePostContainer_'+currForumTopicId).find('div.postContainer');
       $currentSelected.removeClass('HotKeysingleReplyContainer');
    }
    else
    {
        $focusResponse = $('#SinglePostContainer_'+currForumTopicId).find('span.hotKey_'+keyCount);
        if($focusResponse.length == 0)
        {
            return false;
        }
        $currentSelected.removeClass('HotKeysingleReplyContainer');
        $focusResponse.addClass('HotKeysingleReplyContainer');
    }    
    var currResponseTop = $focusResponse.offset().top;
    //$(window).animate({scrollTop:currResponseTop},500);
    $('html,body').animate({scrollTop:currResponseTop-10},500);
    $('#SinglePostContainer').data('currentFocusResponse',$focusResponse);
    
}//function toSetFocusOnCurrResponse($currentSelected,isProvide)          