/*  For prev-next in article page */
$(document).ready(function() {
        //organize the data properly
        var data = 'url=' + window.location + '&type=pre-next';

        var page_type =  $("meta[property='og\\:type']").attr("content");
        if(page_type == 'article')
        {
                //start the ajax
                $.ajax({
                //this is the php file that processes the data and send mail
                url: "/scripts/cms/getArticleDetails.php",
                //GET method is used
                type: "GET",
                //pass the data        
                data: data,    
                //Do not cache the page
                cache: false,
                //success
                success: function (str) {
                        var nav = document.createElement('div'); 
                        nav.setAttribute('id', 'pre-next'); 
                        document.body.appendChild(nav);
                        document.getElementById('pre-next').innerHTML = str;
                        //$("pre-next").html(str);
                }
                });
        }
});
/*  End of prev-next in article page */


/* Related link - plugin */

function pluginRelatedLinks() {
	var tags = $("div #tag_container").html();
	$("div #tag_container").each(function(index) {
			tagsContent = $(this).text();
			tags = tagsContent.replace("Topics:", "");
	});
	var pageURL = "/scripts/cms/getArticleDetails.php?type=dynamic-relatedlinks&tags="+encodeURIComponent(tags)+"&self_url="+document.location.href;
	var status = AjaxRequest.get(
			{
			'url':pageURL,
			'onSuccess':function(req){
			content = req.responseText;
			//if(document.getElementById('relatedlink_container'))
			//document.getElementById('related_cont_display').innerHTML = content;
			//},
			if(document.getElementById('related_cont_display'))
			document.getElementById('related_cont_display').innerHTML = content;
			},
			'onError':function(req){ document.getElementById('related_cont_display').innerHTML = '';}
			}
			);
}




/* For ad purpose */

$(document).ready(function() {
	var url = document.location.href;
	var pattern = /\/([0-9][a-z]-_)*\//g;
	var url_section = url.split('/');
	var number_pattern = /^[0-9]+$/;
	var topic_pattern = /search\.html\?topic=(.*)/g;
	var search_pattern = /\?q=(.*)&/g;
	var file_pattern = /(.*)\.html/i;
	var ga_value = '';
	var domain_varifier = /(.*)\.boldsky\.com/g;
	var file_chunk = '';
	var value = '';
	for(var i=1; i<url_section.length;i++)
	{
		ga_value = url_section[i];
		if(!ga_value.match(number_pattern) && ga_value.length > 0 )
		{
			if(ga_value.match(topic_pattern))
			{
				GA_googleAddAttr("topic",RegExp.$1);
			}
			else if(ga_value.match(file_pattern))
			{
				ga_value = ga_value.replace('_','-');
				ga_value = ga_value.replace('.html','');
				file_chunk = ga_value.split('-');
				for(var x in file_chunk)
				{
					if(!file_chunk[x].match(number_pattern) && !file_chunk[x].match(file_pattern))
					{
						GA_googleAddAttr("topic",file_chunk[x]);
					}
				}
			}
			else if(ga_value.match(search_pattern))
			{
				GA_googleAddAttr("topic",RegExp.$1);
			}
			else    
			{
				if(url_section[i].match(domain_varifier))
					value = RegExp.$1;
				else
					value = url_section[i];
				
				GA_googleAddAttr("topic",value);
			}
		}
	}
	
// To disable the bottom social media
if(screen.width <= 1024 )
document.getElementById('socialLinksBottom').style.display='block';
else
$("#socialLinksBottom").html('');	

// call for related link plug in

	(function(d, s, id) {
	 var js, fjs = d.getElementsByTagName(s)[0];
	 if (d.getElementById(id)) return;
	 js = d.createElement(s); js.id = id;
	 js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
	 fjs.parentNode.insertBefore(js, fjs);
	 }(document, 'script', 'facebook-jssdk'));	

/* to copy    */

document.body.oncopy = function() { 
	var body_element = document.getElementsByTagName('body')[0];
	var selection;
	selection = window.getSelection();
	var pagelink = "<br /><br /> Read more at: <a href='"+document.location.href+"'>"+document.location.href+"</a><br />"; // change this if you want
	var copytext = selection + pagelink;
	var newdiv = document.createElement('div');
	//newdiv.style.position='absolute';
	//newdiv.style.left='-99999px';
	body_element.appendChild(newdiv);
	newdiv.innerHTML = copytext;
	selection.selectAllChildren(newdiv);
	window.setTimeout(function() {
			body_element.removeChild(newdiv);
			},0);
};

	
});

/*     */
//from socail share and newsletter box on right include



var offsetxpoint=-200 //Customize x offset of tooltip
var offsetypoint=20 //Customize y offset of tooltip
var ie=document.all
var ns6=document.getElementById && !document.all
var enabletip=false
if (ie||ns6)
var tipobj=document.all? document.all["dhtmltooltipbs"] : document.getElementById? document.getElementById("dhtmltooltipbs") : ""

function ietruebody(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function ddrivetipbs(thetext, thecolor, thewidth){
if (ns6||ie){
if (typeof thewidth!="undefined") tipobj.style.width=thewidth+"px"
if (typeof thecolor!="undefined" && thecolor!="") tipobj.style.backgroundColor=thecolor
tipobj.innerHTML=thetext
enabletip=true
return false
}
}

function positiontipbs(e){
if (enabletip){
var curX=(ns6)?e.pageX : event.clientX+ietruebody().scrollLeft;
var curY=(ns6)?e.pageY : event.clientY+ietruebody().scrollTop;
//Find out how close the mouse is to the corner of the window
var rightedge=ie&&!window.opera? ietruebody().clientWidth-event.clientX-offsetxpoint : window.innerWidth-e.clientX-offsetxpoint-20
var bottomedge=ie&&!window.opera? ietruebody().clientHeight-event.clientY-offsetypoint : window.innerHeight-e.clientY-offsetypoint-20

var leftedge=(offsetxpoint<0)? offsetxpoint*(-1) : -1000

//if the horizontal distance isn't enough to accomodate the width of the context menu
if (rightedge<tipobj.offsetWidth)
//move the horizontal position of the menu to the left by it's width
tipobj.style.left=ie? ietruebody().scrollLeft+event.clientX-tipobj.offsetWidth+"px" : window.pageXOffset+e.clientX-tipobj.offsetWidth+"px"
else if (curX<leftedge)
tipobj.style.left="5px"
else
//position the horizontal position of the menu where the mouse is positioned
tipobj.style.left=curX+offsetxpoint+"px"

//same concept with the vertical position
if (bottomedge<tipobj.offsetHeight)
tipobj.style.top=ie? ietruebody().scrollTop+event.clientY-tipobj.offsetHeight-offsetypoint+"px" : window.pageYOffset+e.clientY-tipobj.offsetHeight-offsetypoint+"px"
else
tipobj.style.top=curY+offsetypoint+"px"
tipobj.style.visibility="visible"
}
}

function hideddrivetipbsbs(){
if (ns6||ie){
enabletip=false
tipobj.style.visibility="hidden"
tipobj.style.left="-1000px"
tipobj.style.backgroundColor=''
tipobj.style.width=''
}
}

document.onmousemove=positiontipbs








// share this article box

	function getDocHeight() {
		var D = document;
		return Math.max(
			Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
			Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
			Math.max(D.body.clientHeight, D.documentElement.clientHeight)
		);
	}

	function mail2Friend(){
		var f = document.getElementById('mail2frame');
		f.src = "http://telugu.boldsky.com/scripts/mail-print/mail2friend.php";
		var ht = getDocHeight()+ 400;
		document.getElementById('fade').style.height=ht+'px';
		document.getElementById('fade').style.display  = 'block';
		document.getElementById('fixme').style.display = 'block';		
		eventTracker('right-include-email','link', "'"+document.location.href+"'");
	}

	function closeMail2Friend(){
		document.getElementById('fade').style.display  = 'none';
		document.getElementById('fixme').style.display = 'none';
		window.frames['mail2frame'].document.getElementById("uremail").value='';
		window.frames['mail2frame'].document.getElementById("ursfriendsemail").value='';
		window.frames['mail2frame'].document.getElementById("comments").value='';
		window.frames['mail2frame'].document.getElementById("security_code").value='';
		//window.frames['mail2frame'].document.getElementById("err_block").innerHTML='';
	}




var video_ad_flag = true;
function handleMouseDown()
{
	if(video_ad_flag)
	{
		var x = document.createElement('iframe');
		x.setAttribute("src","/common/article-video-ad.html");
		x.setAttribute("width","350");
		x.setAttribute("height","280");
		x.setAttribute("frameborder","0");
		x.setAttribute("scrolling","0");
		document.getElementById('video_ad').appendChild(x);
	}
}
function invokeLatestVideo()
{
	var self_url = document.location.href;
        self_url = self_url.replace('http://hindi.boldsky.com/','');
	var tag_name = '';
        var pageURL = "/scripts/cms/index.php?action=tag-video&tag="+tag_name;
        var status = new AjaxRequest.get(
               {
                       'url':pageURL,
                       'onSuccess':function(req2){
                                        var content = req2.responseText;
                                        if( content.length > 0 )
                                        {
                                                if(document.getElementById('video_on_tag'))
                                                   document.getElementById('video_on_tag').innerHTML = content;
                                        }

                               },
                       'onError':function(req2){
                                        }
               }
        );
	return;

}
function adPlacer()
{
	var img_ad = '';
	if(document.getElementById('newsletter_ad_container') && document.getElementById('newsletter_ad_loader'))
	{
		img_ad = document.getElementById('newsletter_ad_loader').innerHTML;
		document.getElementById('newsletter_ad_container').innerHTML = img_ad;
	}
	if(document.getElementById('article_mid_google_loader') && document.getElementById('article_mid_google'))
	{
		img_ad = document.getElementById('article_mid_google_loader').innerHTML;
		document.getElementById('article_mid_google').innerHTML = img_ad;
	}
}
function showDiv(){
	if(document.getElementById('addImg') && document.getElementById('videoImg'))
	{
		document.getElementById('addImg').style.display = 'block';
		document.getElementById('videoImg').style.display = 'none';
	}
}
function hideDiv(id){
	if(document.getElementById('addImg') && document.getElementById('videoImg'))
	{
		video_ad_flag = false;
		document.getElementById('videoImg').style.display = 'block';
		document.getElementById('addImg').style.display = 'none';
		//if(document.getElementById('video_ad'))
		//	document.getElementById('video_ad').innerHTML = '';
	}
}





// moving ad down at some interval
function shiftAdDown( section )
{
	if(document.getElementById('content_portion'))
	{
		document.getElementById('content_portion').style.display = 'block';
	}
	
	return;
}


var upnext_cat_id = 1;

function checkUserPresence()
{
	var pageURL = "/scripts/cms/getArticleDetails.php?type=user_info&source_url="+window.location.href;
        var status = AjaxRequest.get(
               {
                       'url':pageURL
                       ,'onSuccess':function(req){
                                       content = req.responseText;
					//alert(content);
                                        if( content.length > 0 )
                                        {
                                                document.getElementById('user_info').innerHTML = content;
                                        }

                               }
                       ,'onError':function(req){ document.getElementById('user_info').innerHTML = '';}
               }
       );

	return;
}

function showRelatedTopics()
{
	if(document.getElementById('tags_container'))
	{
		document.getElementById('tags_container').style.display = 'none';
		var tag_output = document.getElementById('tags_container').innerHTML;

		if(document.getElementById('tag_output'))
		{
			document.getElementById('tag_output').innerHTML = tag_output;
		}
	}
}

function invokeDidUMiss( category_id,category_name ) // for the category_id
{
	upnext_cat_id = category_id;
	return;
       var pageURL = "/scripts/cms/getArticleDetails.php?category_id="+category_id+"&type=did-u-miss&category_name="+category_name;
       var status = AjaxRequest.get(
               {
                       'url':pageURL
                       ,'onSuccess':function(req){
                                       content = req.responseText;
					if( content.length > 0 )
					{
						if(document.getElementById('did-u-miss'))
							document.getElementById('did-u-miss').innerHTML = content;
					}
                                       
                               }
                       ,'onError':function(req){ document.getElementById('did-u-miss').innerHTML = '';}
               }
       );

	return;

}


function invokeOnLine( html_id )
{
	if(document.getElementById(html_id))
		html_id = html_id;
	else
		html_id = html_id.id;


	var index = document.getElementById(html_id).selectedIndex;
	var story_tag = document.getElementById(html_id).options[index].text;

	var self_url = window.location.href;
	var category_name = self_url.split('/')[3];

	var pageURL = "/scripts/cms/getArticleDetails.php?tag_name="+story_tag+"&type=latest-story&tag_index="+index+"&category_name="+category_name;
	var status = AjaxRequest.get(
			{
			'url':pageURL
			,'onSuccess':function(req){
			content = req.responseText;
			if( content.length > 0 )
			{
			document.getElementById('latest_story').innerHTML = content;
			}

			}
			,'onError':function(req){ document.getElementById('latest_story').innerHTML =''; }
			}
			);


	return;
}







function showTopics()
{
        var body_content = '';
        var new_content = '', patt = '';
        var topics = '',tag_arr = '',story_content = '';
        body_content = document.getElementsByTagName('div');
        for( var x in body_content )
        {
                if( body_content[x].className == 'article_middle_width' )
                {
                        story_content = body_content[x].innerHTML;
                        var strpos = story_content.indexOf('Tags:');
                        var nst = parseInt(strpos)+13;
                        if(strpos == -1 )
                        {
                                strpos = story_content.indexOf('Topics:');
                                nst = parseInt(strpos)+15;
                        }

                        var endpos = story_content.indexOf("</p>",nst);
                        filter_content = strip_tags(story_content.substring(nst,endpos));
                        tag_arr = filter_content.split(',');
                        for( var tag in tag_arr )
                        {
                                patt = trim(tag_arr[tag]);
                                patt = '/'+patt+'/gi';

                                if( story_content.match(eval(patt)) && story_content.match(eval(patt)).length > 1 )
                                {
					return;
					var tag_val = trim(tag_arr[tag]).replace(/\s+/gi,'-');
                                        patt = trim(tag_arr[tag]);
                                        patt = '/'+patt+'/i';

                                        new_content = '<span style="color:blue;"><a href="/search.html?topic='+tag_val+'" style="text-decoration:none;">'+trim(tag_arr[tag])+'</a></span>';

                                        story_content = story_content.replace(eval(patt),new_content);
                        		body_content[x].innerHTML = story_content; //filter_content;
                                }
                        }
                }
        }
}
function fetchRelatedStories()
{
        var self_url = document.location.href;
	//if(self_url.match(/\/temp\//) != null )
	//{
		var tag_content = document.getElementById('tag_output').innerHTML;
		var pattern = /<a(.*)href="\/search\.html\?topic=(.*)"(.*)>(.*)<\/a>/;
		var values = tag_content.match(pattern);
		/*if(document.getElementById('related_story_heading'))
		{
			var heading = document.getElementById('related_story_heading').innerHTML;
			document.getElementById('related_story_heading').innerHTML = values[4]+' '+heading;			
		}*/
		if(document.getElementById('related_stories'))
		{
			var tag_output = document.getElementById('related_stories').innerHTML;
			if(document.getElementById('stories_container'))
			{
				document.getElementById('stories_container').innerHTML = tag_output;
			}
		}
	//}
}
// Javascript Trim() function
function trim(str){
    if (str == null){return ("");}
          return str.replace(/(^\s+)|(\s+$)/g,"");
}
//                //Strip html tags
function strip_tags( str ){
return str.replace(/<\/?[^>]+>/gi, '');
}
//
// Function to submit article vote ends




function track(id,once) {
    if(!(o=p_o(id)))return;
    if(once && troflags[id]){
        return;
    }
    var d=o.innerHTML;
    var urls=d.split(",");
    if(once)troflags[id] = 1;
}
function clrT(){
    if(to){
        clearTimeout(to);
    to=null;
    }
}



function getdldur(dlnum) {
    if (o=p_o('dlcyc'+dlnum)) {
        return (o.innerHTML * 1500);
    }
    return dldur;
}

function getUserCityAndCountry(sub_frm)
{
        var self_url = document.location.href;
        var pageURL = "/scripts/cms/getArticleDetails.php?type=get-city";
        var status = new AjaxRequest.get(
               {
                       'url':pageURL,
                       'onSuccess':function(req2){
									var content = req2.responseText;
									content_arr = content.split("-!@#-");
									city = content_arr[0];
									country = content_arr[1];
									document.getElementById('newsletter_city').value = city;
									document.getElementById('newsletter_country').value = country;
									sub_frm.submit();
                               },
                       'onError':function(req2){}
               }
        );

        return false;
}


function getMoreNews(thisid,category_id,start,limit){
    $(".msgcolor").hide('');
    $('div.rightInlcudePagination').html('<center><img src="/images/show-news-loader.gif" alt="Loading..." title="Loading..." /></center>');
url="/scripts/cms/index.php?action=dynamic-page&type=rightInclude&category_id="+category_id+"&start="+start+"&limit="+limit;
    $.post(url, function(res){

        var html = res.split("::");
        if(html[0]==0){
            $('div.rightInlcudePagination').hide();
            $('div.rightInlcudePagination').empty();
            $("#msg_gal").html(html[1]);
            return;
        }else{
            $('div.rightInlcudePagination').empty();
            $('div.rightInlcudePagination').hide();
            $(".rightInlcudecollection:last").after(res);
        }
    });
}




//newsletter script




function selectTextById()
{
	if(document.getElementById('email').value == 'Enter email id')
		document.getElementById('email').select()
}


function checkById(){
	//var name=document.getElementById('username').value;
	
	//var nameFilter= "/^[a-zA-Z0-9_-\.]+$/";
	
	
        if(!document.getElementById('email').value.match(/^[\w\_\-\.]+\@[\w\_\-\.]+\.[\w\_\-\.]+$/)){ 
            alert('Please enter correct email id');
            return false;
        }
            return true;
}

function postform(act,form){
   form.action1.value=act;
   form.method='post';
   if(check()){
      form.submit();
      return true;
   }else{
      return false;
   }
}
function postformById(act,form){
   form.action1.value=act;
   form.method='post';
   if(checkById()){
      getUserCityAndCountry(form);
      //form.submit();
      return false;
   }else{
      return false;
   }
}

function selecttext()
{
	document.newsletter_subscribeform.email.select()
}

//script for newsletter subscription
function selectTextById()
{
	if(document.getElementById('email').value == 'Enter email id')
		document.getElementById('email').select()
}




// sticky by mukesh
			$.fn.stickyfloat = function(options, lockBottom) {
				var $obj 				= this;
				var parentPaddingTop 	= parseInt($obj.parent().css('padding-top'));
				var startOffset 		= $obj.parent().offset().top;
				var opts 				= $.extend({ startOffset: startOffset, offsetY: parentPaddingTop, duration: 200, lockBottom:true }, options);
				
				$obj.css({ position: 'absolute' });
				
				if(opts.lockBottom){
					var bottomPos = $obj.parent().height() - $obj.height() + parentPaddingTop;
					if( bottomPos < 0 )
						bottomPos = 0;
				}
				
				$(window).scroll(function () { 
					$obj.stop(); 

					var pastStartOffset			= $(document).scrollTop() > opts.startOffset;	
					var objFartherThanTopPos	= $obj.offset().top > startOffset;	
					var objBiggerThanWindow 	= $obj.outerHeight() < $(window).height();	

					if( (pastStartOffset || objFartherThanTopPos) && objBiggerThanWindow ){ 
						var newpos = ($(document).scrollTop() -startOffset + opts.offsetY );
						if ( newpos > bottomPos )
							newpos = bottomPos;
						if ( $(document).scrollTop() < opts.startOffset ) 
							newpos = parentPaddingTop;
			
						$obj.animate({ top: newpos }, opts.duration );
					}
				});
			};



// sticky for header navigation by mukesh
$(function() {
		// Check the initial Poistion of the Sticky Header
		var stickyHeaderTop = $('#headerFixed').offset().top;

		$(window).scroll(function() {
			if ($(window).scrollTop() > stickyHeaderTop) {
				$('#headerFixed').css({
					position : 'fixed',
					top : '0px'
				});
			} else {
				$('#headerFixed').css({
					position : 'relative',
					top : '0px',
					margin : '0px',
					width : '988px'
				});
			}
		});
	}); 


	// previous next for article by kalapana
	$(document).ready(function() {
		$('#socialLinksLeft').stickyfloat({
			duration : 600
		});
		$("body").keyup(function(e) {
			if($("div.closegoogleBlock").is(":visible")){
				if(e.keyCode == 37) { // left
					$("div.sliderPrev:visible > a").trigger("click");
				}else if(e.keyCode == 39) { // right
					$("div.sliderNext:visible > a").trigger("click");
				}else if(e.keyCode == 27)
					$("div.closegoogleBlock:visible > a").trigger("click");
			}else{
				if(e.keyCode == 37 && $(".prevArticle").attr("href")) { // left
					window.location.href = $(".prevArticle").attr("href");
				}else if(e.keyCode == 39 && $(".nextArticle").attr("href")) { // right
					window.location.href = $(".nextArticle").attr("href");
				}

			}
		});
	}); 
