
$(function(){
    var location = window.location;
    CYWObject.init();
    CYWObject.hebrewDate();
    CYWObject.searchBoxContentSwitch();
    CYWObject.contactForm(); 
    
});

var CYWObject = {
    init:function (){
	$('.error').hide();
    },
    
    hebrewDate : function () {
	
	// First display the Hebrew date
	var now = new Date;
	var tday = now.getDate();
	var tmonth = now.getMonth() + 1;
	var tyear = now.getYear();
	if(tyear < 1900)
            // if date from Netscape, then add 1900
            tyear += 1900;
	var hebDate = civ2heb(tday, tmonth, tyear);
	var hmS = hebDate.substring(hebDate.indexOf(' ')+1, hebDate.length);
	var	hDay = eval(hebDate.substring(0, hebDate.indexOf(' ')));
	var hMonth = eval(hmS.substring(0, hmS.indexOf(' ')));
	var hYear = hmS.substring(hmS.indexOf(' ')+1, hmS.length);
	$("#hebdate").append('Hebrew Date:&nbsp; ' + hebMonth[hMonth+1] + ' ' + hDay + ', ' + hYear)
	// Then display the corresponding civil dates
	var day, month, year;
	var today = new Date;
	var yesterday = new Date(today.getTime() - 86400000);
	yday   = yesterday.getDate();
	ymonth = yesterday.getMonth() + 1;
	year  = yesterday.getYear();
	if(year < 1900)
            year += 1900; // if date from Netscape, then add 1900
	tday   = today.getDate();
	tmonth = today.getMonth() + 1;
	year  = today.getYear();4
	if(year < 1900)
            year += 1900; 
	$("#gregdate").append(/*'Gregorian Dates:&nbsp;' +*/ civMonth[ymonth] + ' ' + yday + ', ' + year + '&nbsp;(night of)&nbsp;' + civMonth[tmonth] + ' ' + tday + ', ' + year)
	
	
    },
    searchBoxContentSwitch: function (){
	$('#searchin').bind('focus', function () {
	    /*  $(this).css({
		color: '#0d2255',
		"font-weight": "bold"
		}) */
	    $(this).val("");
	    
	}); 
	
	$('#searchin').bind('blur', function () {
	    $(this).val(function (i, val) {
		if (val == ""){
		    return "Search"
		}
	    }); 
	    /* $(this).css({
               color: '#666',
               "font-weight": "normal"
               })*/
	});

    },
    contactForm: function () {
	$("#submit_b").click(function() {
            //  console.log("i got clicked")
            $('.error').hide();
            var submit = $("#submit_b").val();
            var name = $("input#name").val();
            var email = $("input#email").val();
            if (name == "") {
		$("label#name_error").show();
		$("input#name").focus();
		
		return false;
            }
            
            if (email == "") {
		$("label#email_error").show();
		$("input#email").focus();
		
		return false;
            }
            if (!CYWObject.validateEmail(email)) {
		
		$("label#email_error").text("Enter a valid eMail");
		$("label#email_error").show();
		$("input#from").focus();
		return false;
            }
            
            var message = $("#message").val();
            if (message == "") {
		$("label#message_error").show();
		$("#message").focus();
		return false;
            }
            
            var dataString = 'message=' + message + '&email=' + email + '&submit=' + submit + '&name=' + name ;
            // console.log(dataString);
            // alert(dataString);
            
            $.ajax({
		type: "POST",
		url: "/email.asp",
		data: dataString,
		success: function(httpObject, textStatus, jqXHR) {
                    $(':input','form.contactform')
			.not(':button, :submit, :reset, :hidden')
			.val('');
                    $('#sucessmessage').html("Your message has been sent!")
			.append("<p>We will be in touch soon.</p>")
			.delay(10000)
			.slideToggle("slow"); 
                    
		},
		error: function(httpObject, textStatus, jqXHR) {
                    $("#msgerror").fadeIn(40).delay(7000).slideToggle("slow");    
		}
            });
            return false;
	})
    },
    
    validateEmail: function (str) {        
        return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
    },
    pageFeatures: function (pathname) {
	var access_token = "";
	switch (pathname) {
	    
	case "/index.asp":
	case "/":
	    access_token = $("#access_token")[0].innerHTML;
	    CYWObject.getPosts(2, access_token);
	    $('#slider1').anythingSlider({
		startStopped    : false, // If autoPlay is on, this can force it to start stopped
		width           : 755,   // Override the default CSS width 496 × 335
		height          : 367,
		theme           : 'cs-portfolio',
		autoPlayLocked  : true,  // If true, user changing slides will not stop the slideshow
		resizeContents  : true,
		buildArrows     : false,      // If true, builds the forwards and backwards buttons
		buildNavigation : false,      // If true, buildsa list of anchor links to link to each panel
		navigationFormatter : null,      // Details at the top of the file on this use (advanced use)
		easing: 'easeInOutExpo',
		resumeDelay     : 10000, // Resume slideshow after user interaction, only if autoplayLocked is true (in milliseconds).
		onSlideComplete : function(slider){
		    // alert('Welcome to Slide #' + slider.currentPage);
		}
	    });
	    break;
	    
	case "/news.asp":
	    access_token = $("#access_token")[0].innerHTML;
	    CYWObject.getPosts(10, access_token);
	    break;
	    
	default:
            
            break;
	}
	
	
    },
    getPosts: function (limit, access_token){
	//console.log("access_token: "+access_token)	
        var  html = "<ul>"
	//   $.getJSON("https://graph.facebook.com/Community.of.Yahweh.Worldwide/posts?"+access_token+"limit="+limit+"&callback=?", function(json) {
	$.getJSON("https://graph.facebook.com/Community.of.Yahweh.Worldwide/posts?"+access_token, function(json) {
	    
            //console.log(json)
            $.each(json.data, function(i, json) {
 		
                var message = json.message;
                if(typeof json.message === "undefined"){
		    
                }else{
                    if(limit==2){
						  
						message = CYWObject.makeClickable(message, "short");
                        message +="....<a href='/news.asp' > read more</a>"
                    } else {
					message = CYWObject.makeClickable(message, "long");
                    }
                    if(i == 0){
						
                        html += "<li class='ntitle first' ><b style='color:#3B5998!important;'>Update posted "+jQuery.timeago(json.created_time)+"</b></li>"
                        html += "<li class='nbody' style='color:#3D3D3D!important;'>"+CYWObject.insertLineBreaks(message)+"</li>"
                    } else {
                        html += "<li class='ntitle' ><b style='color:#3B5998!important;'>Update posted "+jQuery.timeago(json.created_time)+"</b></li>"
                        html += "<li class='nbody' style='color:#3D3D3D!important;'>"+CYWObject.insertLineBreaks(message)+"</li>"
                    }
                }
		if(limit==2 & i == 1){
		    return false;
		}
            })
                html += "</ul>"
            $(".newsfeed, .news").animate({ opacity:0}, 500, function(){
                $("#loadingsp").hide();
                $("#newsbak").hide();
                $(".newsfeed, .news").append(html);
            });
            $(".newsfeed, .news").animate({opacity:1}, 500);
            
        });
    },
    insertLineBreaks: function (message){
        var message = message.replace(/;/g, ";<br/>")
        message = message.replace(/The Torah: /g, " <br/>The Torah: ")
        return message;
    },
    makeClickable: function(message, status) {
            var pattern = /(ftp|https?):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/i;
			if (status == "long") {
           return  CYWObject.clickableLong(message, pattern);
            }else {
			return	CYWObject.clickableShort(message, pattern);
	 		}
        }, 
	clickableLong: function(message, pattern){
         if(message.match(pattern) == null || message.match(pattern).length ==0){
            return message;            
			} else {
            var href = message.match(pattern)[0];
            var newmessage = message.replace(pattern, "<a target='_blank' href='"+href+"'>"+href+"</a>");
             return newmessage;
			}        
        }, 
    clickableShort: function(message, pattern){
         if(message.match(pattern) == null || message.match(pattern).length ==0){
            message = message.substr(0,125)
            return message;            
			} else {
            var href = message.match(pattern)[0];
            message = message.substr(0,125)
            message = message.replace(pattern, "");
             return message+"  <a target='_blank' href='"+href+"'>"+href+"</a>";
			}        
}
}

$(document).ready(function () {    
    // console.dir($("#access_token")[0].innerHTML)    
    CYWObject.pageFeatures(location.pathname);  
    $("span[class^='arrow']").hide();
    $("#anyslider div.anythingControls").hide();
    $("div.anythingSlider.anythingSlider-cs-portfolio.activeSlider").css({
        padding:0,
        margin:"1px"
    });
    
    if (location.pathname == "/search.asp") {
	//alert(window.location.pathname)
	var searchtext = $("#search-text").val()
	$("#search-results").gSearch({
	    search_text : searchtext,
	    count : 1,
	    site : 'communityofyahweh.org',
	    pagination : false
	});
    }
    /* if($(".connect_widget_image").length != 0)
       alert("Found Fb image")
       else 
       alert("Found Nothing!")
    */
    
})



