$(document).ready(function(){
	changeCaptchaResponseInputColor();

    $(".iframe").fancybox({
            'width'				: '75%',
            'height'			: '75%',
            'autoScale'			: false,
            'transitionIn'		: 'none',
            'transitionOut'		: 'none',
            'type'				: 'iframe'
    });

    

    setTimeout('updateCityStateInfo()',600000);
   // setTimeout('updateCityStateInfo()',1800000);

    memeberLoginForm();
    checkUserNameLength();
    showActiveCities();
    $(".jqSocailShare").click(showSocialBookMarkingBox);
    $("#popupContactClose").click(disablePopup);
    $(".jqCancel").click(disablePopup);

    $(".jqStoryEmail").click(emailPopup);
    $("#emailStoryClose").click(closeEmailStory);
    $(".jqEmailCancel").click(closeEmailStory);
    $(".jqPostStory").click(sendStories);

    $(".jqShortUrlCreate").click(showShortUrlInfo);
    $(".jqShortUrlClose").click(closeShortUrlBox);

   /* $(".jqCopy").bind( 'click', function(){
         var currentLink = $(this);
         var postID      = currentLink.attr('id');
         $("#shortUrlText"+postID).focus();
	 $("#shortUrlText"+postID).select();
	// r=pointer.form.txtShareAlbum.createTextRange();
	 $("#shortUrlText"+postID).copy();
         return false;
    });*/
    $(".jqCopy").click(copyClipBoard);
    $("#sb1").click(showActiveCities);
    $(".jqStoryValidation").click(validateStoryContents);

   // $(".jqStoryValidation").mouseover(changeImaage);

    $(".jqSocailShares").click(shareThis);



  



    //ADDED FOR SHARING THE STORIES TO FACEBOOK WALL WITHOUT LEAVING THE SITE
   // $(".jqFacbookShare").click(shareFacebookStories);
    //$(".close").live('click', closeFacebokPopup);

    $('a.poplight[href^=#]').click(function() {
    $("#emailMessage").html('');
    var currentLink             = $(this);
    var postID                  = currentLink.attr('id');
    $("#hidPostId").val(postID);
   
    var popID = $(this).attr('rel'); //Get Popup Name
    var popURL = $(this).attr('href'); //Get Popup href to define size

    //Pull Query & Variables from href URL
    var query= popURL.split('?');
    var dim= query[1].split('&');
    var popWidth = dim[0].split('=')[1]; //Gets the first query string value

    //Fade in the Popup and add close button
    $('#' + popID).fadeIn().css({'width': Number( popWidth )}).prepend('<a href="#" class="close"><img src="'+base_path+'wp-content/themes/TMAS/images/fancy_close.png" class="btn_close" title="Close Window" alt="Close" /></a>');

    //Define margin for center alignment (vertical   horizontal) - we add 80px to the height/width to accomodate for the padding  and border width defined in the css
    var popMargTop = ($('#' + popID).height() + 80) / 2;
    var popMargLeft = ($('#' + popID).width() + 80) / 2;

    //Apply Margin to Popup
    $('#' + popID).css({
        'margin-top' : -popMargTop,
        'margin-left' : -popMargLeft
    });
   
    //Fade in Background
    $('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
    $('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer - .css({'filter' : 'alpha(opacity=80)'}) is used to fix the IE Bug on fading transparencies

    return false;
});

//Close Popups and Fade Layer
$('a.close, #fade').live('click', function() { //When clicking on the close or fade layer...
    $('#fade , .popup_block').fadeOut(function() {
        $('#fade, a.close').remove();  //fade them both out
    });
    return false;
});

// function to update city and state for each story

});

function checkUserNameLength()
{
    $(".jqRegisterUser").focusout(function(){
        var username = $(".jqRegisterUser").val().length;
        if(username > 25)
            {
                alert("Username cant be this much long");
                return false;
            }
    });
}
function memeberLoginForm()
{
    var user = 'username or alias';
    var pass = 'password';
    $(".jqUsername").val(user);
    $(".jqPassword").val(pass);

    $(".jqUsername").click(function(){
        if($(".jqUsername").val() == user)
            {
                $(".jqUsername").val('').focusout(function()
                    {
                        if($(".jqUsername").val() == ''){
                            $(".jqUsername").val('username or alias');
                        }
                    });
            }
    });
    $(".jqPassword").click(function(){
        if($(".jqPassword").val() == pass)
        {
            $(".jqPassword").val('').focusout(function(){
                if($(".jqPassword").val() == ''){
                    $(".jqPassword").val('password');
                    }
            });
        }
    });
}
function rateThisPost(elm, rate, postID)
{
   // alert(base_path);
   // return false;
   //$('#idoftheelement').attr("disabled", true);

   var ids      = {id: postID, rating: rate};
   var show     = $("#thumbup"+postID);
   var showDown = $("#thumbdown"+postID);
   $.ajax({
            type: "post",
            url: base_path+"wp-content/themes/TMAS/rate.php",
            data: ids,
            dataType: "json",
            beforeSend: function() {
                    if(rate == 'like')
                    {
                       $("#jqRateProgress"+postID).show().css({
								'filter' :opacity=50,
								'opacity':0.5
							});
                    }
                    else if(rate == 'dislike')
                    {
                         $("#jqRateProgress"+postID).show().css({
								'filter' :opacity=50,
								'opacity':0.5
							});
                    }
            },
			complete:function(){
				 $("#jqRateProgress"+postID).hide();
			},
            success: function(data) {
				//alert(data); return false;
                if(data.status == '')
                {
                    if(data.type == 'like')
                    {
                        show.html(data.result);
                        return false;
                    }
                    else if(data.type == 'dislike')
                    {
                        showDown.html(data.result);
                        return false;
                        
                    }
					/*else if(data.type == 'nologin')
					{
						alert("You must be logged in to rate this story!");
						return false;
					}*/
                }
                else
                {
                    alert("You have already rated this story!");
                     return false;
                }
                return false;
            }
			
    });
    return false;
}
function showSocialBookMarkingBox()
{
    var currentLink  = $(this);
    var link         = currentLink.attr('id');
    centerPopup();
    loadPopup(link);
    return false;
}
function loadPopup(link)
{
   //var popupStatus = 0;
   // if(popupStatus==0)
   // {
   // $("#popupContact").slideDown("slow");
    $("#hidLink").val(link);
        //popupStatus = 1;
    //}
}
//centering popup
function centerPopup()
{
    //request data for centering
    
    var windowWidth         = $(window).width();
    var windowHeight        = $(window).height();
    var popupHeight         = $("#popupContact").height();
    var popupWidth          = $("#popupContact").width();
    var pageScrollTop       = document.documentElement.scrollTop ? document.documentElement.scrollTop : (document.body.scrollTop ? document.body.scrollTop : 0);


    var addCommentBoxTop        = pageScrollTop + (windowHeight - popupHeight)/8 ;
    var addCommentBoxLeft       = (windowWidth - popupWidth) / 2;

    $("#popupContact").css({
                    position : "absolute",
                    left : addCommentBoxLeft,
                    top: addCommentBoxTop
                }).slideDown("slow");

    //centering
    /*$("#popupContact").css({
    "position": "absolute",
    "top": windowHeight/2-popupHeight/2,
    "left": windowWidth/2-popupWidth/2
    });
    //only need force for IE6

    $("#backgroundPopup").css({
    "height": windowHeight
    });*/
}
function disablePopup()
{
     //$("#popupContact").fadeOut("slow");
    $("#popupContact").slideUp("slow");
    return false;
}
function somefunction()
{
    var test = this.id;
    alert(test);
    return false;
}
function shareThis()
{
    var currentLink  = $(this);
    var link         = currentLink.attr('id');
    $("#popupContact").slideUp("slow");
    window.open(link,"Share",'scrollbars=auto,resizable=yes,width=600,height=600');
    return false;
}
// FOR SHARING STORIES WITH FRIENDS - POPUP, EMAILING 
function emailPopup()
{
    $("#emailMessage").html('');
    var currentLink             = $(this);
    var postID                  = currentLink.attr('id');
    var windowWidth             = $(window).width();
    var windowHeight            = $(window).height();
    var popupHeight             = $("#emailStory").height();
    var popupWidth              = $("#emailStory").width();
    var pageScrollTop           = document.documentElement.scrollTop ? document.documentElement.scrollTop : (document.body.scrollTop ? document.body.scrollTop : 0);
    var addCommentBoxTop        = pageScrollTop + (windowHeight - popupHeight) /8;
    var addCommentBoxLeft       = (windowWidth - popupWidth) / 2;
    //alert(addCommentBoxTop);
    //return false;

    $("#hidPostId").val(postID);
    $("#emailStory").css({
                    position : "absolute",
                    left : addCommentBoxLeft,
                    top: addCommentBoxTop
                }).fadeIn("slow");
      return false;
}
function closeEmailStory()
{
    $("#Facebook").fadeOut("slow");
    $("#txtYourName").val("");
    $("#txtYourEmail").val("");
    $("#txtShareEmail").val("");
    $('#fade, a.close').remove(); 
    return false;
}
function sendStories()
{
    var name        = $.trim($("#txtYourName").val());
    var yourEmail   = $.trim($("#txtYourEmail").val());
    var email       = $.trim($("#txtShareEmail").val());
    var postID      = $("#hidPostId").val();
    if(name == '')
    {
        alert("Please enter your name");
        $("#txtYourName").focus();
        return false;
    }
    if(yourEmail == '')
    {
        alert("Please enter your email");
        $("#txtYourEmail").focus();
        return false;
    }
    if(yourEmail != '' && !echeck(yourEmail))
    {
        return false;
    }
    if(email == '')
    {
        alert("Please enter email");
        $("#txtShareEmail").focus();
        return false;
    }
    if(email != ''&& !echeck(email))
    {
        return false;
    }
    var params = {id: postID,Name:name,youremail:yourEmail, email: email};
    $.ajax({
             type:"post",
             url: base_path+"wp-content/themes/TMAS/emailstory.php",
             data: params,
             dataType: "json",
             beforeSend: function() {
                 $("#jqLoader").show();
            },
            complete:function(){
               $("#jqLoader").hide();
            },
            success: function(data) {
               // alert(data);return true;
               $("#emailMessage").html(data.message);
               setTimeout('closeEmailStory()',3000);
            }
    });
    return false;
}
/*function showShortUrlInfo()
{
    var currentLink = $(this);
    var postID      = currentLink.attr('id');
    $("#shortUrl"+postID).animate({"height": "toggle"}, {duration: 1000},{width:"545px"}, 500, function(){
            this.focus();
            this.select();
        }).css("color","#614A3E");

   /* $("#shortUrl"+postID).fadeIn("slow");*/
  /*  $("#shortUrlText"+postID).focus();
    $("#shortUrlText"+postID).select();
    $(this).mouseup(function(e){
         e.preventDefault();
     });

    return false;
}*/
function showShortUrlInfo()
{
   var currentLink = $(this);
   var postID      = currentLink.attr('id');
   var className   = currentLink.attr('class');
   if(className == 'jqShortUrlClose')
   {
	   $("#shortUrl"+postID).hide("slow");
	   $(currentLink).removeClass('jqShortUrlClose').addClass('jqShortUrlCreate');
   }
   else
   {
	   $("#shortUrl"+postID).show("slow", function(){
		   $(currentLink).removeClass('jqShortUrlCreate').addClass('jqShortUrlClose');
		   $("#shortUrlText"+postID).focus();
		   $("#shortUrlText"+postID).select();
	   });
   }
   return false;
}
function closeShortUrlBox()
{
	 var currentLink = $(this);
     var postID      = currentLink.attr('id');
     $("#shortUrl"+postID).hide("slow");
	 $('#'+postID).removeClass('jqShortUrlClose').addClass('jqShortUrlCreate');
	 return false;
}

function copyClipBoard()
{
    var currentLink = $(this);
    var postID      = currentLink.attr('id');
    //$("#shortUrlText"+postID).copy()
    /* $("input#my-button-id").bind( 'click', function() {
                        $("div#TEST-ONE").copy();
                    });*/
    var text = $("#shortUrlText"+postID).val();
    $.copy(text);
    //$("#shortUrlText"+postID+" input").copy();
   /* if (window.clipboardData)
   {
           window.clipboardData.setData("Text", text);
   }
   else if (window.netscape)
   {
        netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
        var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
        if (!clip)
            return;
        var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
        if (!trans)
            return;
        trans.addDataFlavor('text/unicode');
        var str = new Object();
        var len = new Object();
        var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
        var copytext=text;
        str.data=copytext;
        trans.setTransferData("text/unicode",str,copytext.length*2);
        var clipid=Components.interfaces.nsIClipboard;
        if (!clip)
            return false;
       clip.setData(trans,null,clipid.kGlobalClipboard);
   }*/
  
   return false;
}
function showActiveCities()
{
   $.ajax({
       url: base_path+"wp-content/themes/TMAS/mostactivecities.php",
       dataType: "html",
       beforeSend:function(){
             $("#text-5").html('<div style="height:200px;"><img src="/wp-content/themes/TMAS/images/loading.gif" style="margin-left:120px;margin-top:80px;" /></div>');
       },
       complete:function(){
         //$("#text-5").html('');
       },
       success:function(data){
           //alert(data); return false;
        $("#text-5").html(data);
       }
   });
   
}

function echeck(str)
{

    var at="@"
    var dot="."
    var lat=str.indexOf(at)
    var lstr=str.length
    var ldot=str.indexOf(dot)
    if (str.indexOf(at)==-1){
       alert("Invalid E-mail ID")
       return false
    }

    if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
       alert("Invalid E-mail ID")
       return false
    }

    if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
        alert("Invalid E-mail ID")
        return false
    }

     if (str.indexOf(at,(lat+1))!=-1){
        alert("Invalid E-mail ID")
        return false
     }

     if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
        alert("Invalid E-mail ID")
        return false
     }

     if (str.indexOf(dot,(lat+2))==-1){
        alert("Invalid E-mail ID")
        return false
     }

     if (str.indexOf(" ")!=-1){
        alert("Invalid E-mail ID")
        return false
     }
     return true
}
function validateStoryContents()
{
    var title = $("#txtStoryTitle").val();
    var city  = $("#txtCity").val();
    var state = $("#txtState").val();
    var story = $("#txtMessage").val();
   /* if(title == '')
    {
        alert("Please enter title");
        $("#txtStoryTitle").focus();
        return false;
    }
    if(title != '' && title.length > 23)
    {
        alert("Title cant be this much long!");
        $("#txtStoryTitle").focus();
        return false;
    }
    if(city == '')
    {
        alert("Please enter city");
        $("#txtCity").focus();
        return false;
    }
    if(state == '')
    {
        alert("Please enter state");
        $("#txtState").focus();
        return false;
    }
    if(story == '')
    {
        alert("Please enter message");
        $("#txtMessage").focus();
        return false;
    }
    /* if(story != '' && story.length > 500)
    {
        alert("Message cant be this much long!");
        $("#txtMessage").focus();
        return false;
    }*/
    return true;    
}
function shareFacebookStories()
{
    var popID = $(this).attr('rel'); //Get Popup Name
    var popURL = $(this).attr('href'); //Get Popup href to define size

    //Pull Query & Variables from href URL
    var query= popURL.split('?');
    var dim= query[1].split('&');
    var popWidth = dim[0].split('=')[1]; //Gets the first query string value

    //Fade in the Popup and add close button
    $('#' + popID).fadeIn().css({'width': Number( popWidth )}).prepend('<a href="#" class="close"><img src="'+base_path+'wp-content/themes/TMAS/images/close_pop.png" class="btn_close" title="Close Window" alt="Close" /></a>');

    //Define margin for center alignment (vertical   horizontal) - we add 80px to the height/width to accomodate for the padding  and border width defined in the css
    var popMargTop = ($('#' + popID).height() + 80) / 2;
    var popMargLeft = ($('#' + popID).width() + 80) / 2;

    //Apply Margin to Popup
    $('#' + popID).css({
        'margin-top' : -popMargTop,
        'margin-left' : -popMargLeft
    });

    //Fade in Background
    $('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
    $('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer - .css({'filter' : 'alpha(opacity=80)'}) is used to fix the IE Bug on fading transparencies

    return false;
}
function closeFacebokPopup()
{
   $('a.close, #fade').live('click', function() { //When clicking on the close or fade layer...
    $('#fade , .popup_block').fadeOut(function() {
        $('#fade, a.close').remove();  //fade them both out
    });
    return false;
})}
/*
//Close Popups and Fade Layer
$('a.close, #fade').live('click', function() { //When clicking on the close or fade layer...
    $('#fade , .popup_block').fadeOut(function() {
        $('#fade, a.close').remove();  //fade them both out
    });
    return false;

}**/

function updateCityStateInfo()
{
   // alert("here");
    $.ajax({
       url: base_path+"wp-content/themes/TMAS/updatecitystateinfo.php",
       dataType: "html",
       beforeSend:function(){
             
       },
       complete:function(){
         
       },
       success:function(data){
         // alert(data); return false;
        // $("#text-5").html(data);
       // setTimeout('updateCityStateInfo()',1800000);
        setTimeout('updateCityStateInfo()',600000);
       }
   });
}
function changeCaptchaResponseInputColor()
{
	$("#recaptcha_response_field").add('input').css('border-color', '#D2D2D2');
	

}
