
/* *************************************************************************
Title : Common JS
Author : Colossal Squid Industries
Description : Main JS file for global functions, and document.ready functions
Created : May 5, 2010
Modified : 


JS TOC
//DOCUMENT READY
=INIT NAV OVER 
=VIVA FOOTER INIT
=OVERLAY INIT

//GLOBAL FUNCTIONS
=BANNER HOVER
=BANNER OUT
=NAV OVER
=SHOW SUCCESS (FACEBOOK AND TWITTER)
=SOCIAL CLOSE (FACEBOOK AND TWITTER SUCCESS)
=OPEN MODALS
=INIT MODAL WINDOWS
=PREVIEW FORM
=FACEBOOK AND TWITTER POSTING
************************************************************************* */
//BEGIN DOCUMENT READY

$(document).ready(function () {


    // INIT NAV OVER 
    // Top nav background toggle
    var parentClass = $('.navigation ul').attr('class');

    $(".navigation li").hover(
	  function () {
	      navOver($(this));
	  },
	  function () {
	      navOut($(this), parentClass);
	  }
	);

    if (navigator.userAgent.indexOf('Windows') == -1) {
        $("textarea").css("overflow", "hidden");
    }


    // VIVA FOOTER INIT
    /* Updated 6/1, KM - needed to change class name entirely 
    IE6 doesn't understand multiple class */
    $(".viva_footer_callout_left").mouseover(function () {
        bannerHover($(this));
        //	$(".viva_footer_callout_right").addClass("hover")
    });
    $(".viva_footer_callout_right").mouseover(function () {
        //	$(".viva_footer_callout_right").addClass("hover") 
        bannerHover($(this));
    });

    $(".viva_footer_callout_left").mouseout(function () {
        bannerOut($(this));
        //	$(".viva_footer_callout_right").removeClass("hover")
    });
    $(".viva_footer_callout_right").mouseout(function () {
        bannerOut($(this));
        //	$(".viva_footer_callout_right").removeClass("hover")  
    });

    $("#viva_commentpanel_contents textarea").click(function () {
        $("#viva_commentpanel_contents p").html("");
    });

    $("#viva_commentpanel_contents p").click(function () {
        $("#viva_commentpanel_contents p").html("");
        $("#viva_commentpanel_contents textarea").focus();
    });
    $("#viva_btn_clear").click(function () {
        $("#viva_commentpanel_contents p").html("");
        $("#viva_commentpanel_contents textarea").val("");
        $("#viva_commentpanel_contents textarea").focus();
        return false;
    });

    $("#viva_footer_toggle_btn").click(function () { hideFooter() });
    // END OF VIVA FOOTER INIT



    //OVERLAY INIT
    $('.modalOverlay').click(function () {
        $(this).hide();

    });

	
	$('.openModal').click(function(){
		var thisDiv = $(this).attr('href');
		openModal(thisDiv);
		return false;
	});
	

});               //END DOCUMENT READY



/***************************************************************************/		

//GLOBAL FUNCTIONS





/* *************************************************************************
=BANNER HOVER
************************************************************************* */
function bannerHover(thisEl){
		//gets the classes
		var classes = $(thisEl).attr('class');
		
		//finds the second class
		//convention for these classes is "viva_footer_callout_left callout"
		var splitClass = classes.split(" ")[1];
		
		
		//removes original class and appeneds "callout_hover"
		$(thisEl).removeClass(splitClass);
		$(thisEl).addClass(splitClass +"_hover");
}

/* *************************************************************************
=BANNER OUT
************************************************************************* */
function bannerOut(thisEl){
	//gets the classes
	var classes = $(thisEl).attr('class');
	
	//finds the second class
	//convention for these classes is "viva_footer_callout_left callout_hover"
	var splitClass = classes.split(" ")[1];
	
	//removes the "_hover" from the second class
	var replaceClass = splitClass.replace("_hover", "");
	
	//removes "_hover" class and adds original 
	$(thisEl).removeClass(splitClass);
	$(thisEl).addClass(replaceClass);
	
}
/* *************************************************************************
=NAV OVER
Nav hover images are larger then their resting states
JS was needed for the swap, as the partent image changes, rather then the alink img
This is a simple show/hide dependent on the css class of the li
************************************************************************* */
function navOver(thisLi){


    var thisClass = $(thisLi).attr('class');

	switch(thisClass)
	{
	case "products":
	     $(thisLi).parent().attr('class', 'productsActive');
	     $(thisLi).children('ul').css('display', 'block');
	     break;
	case "savings":
	    $(thisLi).parent().attr('class', 'savingsActive');
		 $(thisLi).children('ul').css('display', 'block');
	  break;
	case "commercial":
	    $(thisLi).parent().attr('class', 'commercialActive');
		 $(thisLi).children('ul').css('display', 'block');
	    break;
	default:
		break
	}
	
}
/* *************************************************************************
=NAV OVER
************************************************************************ */
function navOut(thisLi,parentClass){

	//parent class is global var -> $('.navigation ul').attr('class');
	
	
	var thisClass = $(thisLi).attr('class');
	switch(thisClass)
	{
	case "products":
	  $(thisLi).parent().attr('class', parentClass);
	  $(thisLi).children('ul').css('display', 'none');
	  break;
	case "savings":
	    $(thisLi).parent().attr('class', parentClass);
		$(thisLi).children('ul').css('display', 'none');
	  break;
    case "commercial":
        $(thisLi).parent().attr('class', parentClass);
		$(thisLi).children('ul').css('display', 'none');
        break;
	default:
	 	break;
	}
	
}

//HIDE THE FOOTER
function hideFooter()
{
	$("#viva_footer").animate({bottom: '-230px'});
	$("#viva_footer_toggle_btn").unbind("click");
	$("#viva_footer_toggle_btn").click(function(){showFooter()});
}
function showFooter()
{
	$("#viva_footer").animate({bottom: '0px'});
	$("#viva_footer_toggle_btn").unbind("click");
	$("#viva_footer_toggle_btn").click(function(){hideFooter()});
}

//BACKGROUND SWAP
function callback(color) {


   
}
function background_swap(color) {

    $('body').removeClass("red orange green").addClass(color);

 /*   var newWrapper = document.createElement("div");
    newWrapper.setAttribute("class", "transition " + color);
    $(".mainContentWrapper").append(newWrapper);
    $(newWrapper).height($(".mainContentWrapper").height());

    if ($(".page").length > 0) {
        $(".mainContent .page_top").children().css({
        "position" : "relative",
        "z-index" : 500
        });

        var newPage = document.createElement("div");
        var newPageTop = document.createElement("div");

        newPage.setAttribute("class", "page transition " + color);
        newPageTop.setAttribute("class", "page_top " + color);

        newPage.appendChild(newPageTop);
        $(".mainContent").append(newPage);

        $(newPage).fadeIn("slow");
    }
    
    $(newWrapper).fadeIn("slow", function () {
        $("body").removeClass("orange");
        $("body").removeClass("red");
        $("body").removeClass("green");

        $("body").addClass(color);

     $(newWrapper).remove();
        if ($(".page").length > 0) {
            $(newPage).remove();
        }
    }); */

}





/* *************************************************************************
=SHOW SUCCESS (FACEBOOK AND TWITTER)
Shows the modal window on a successful post of a fb or twitter message
Function is called on page load, if appropriate query string is present
var source is set when the function is called
source will either be "facebook" or "twitter"
************************************************************************* */
function showSuccess(source) {
    
    // Need use a cookie to get the post, FB cache is too slow for true updates
    //tracking cookies so user doesn't see success on refresh
    var savedPost = readCookie('socialPost');
    if (savedPost == null) { return false; }
    
    //Init the overlay
    $('#socialSuccess').jqm({
        overlayClass: 'modalOverlay',
        onShow: loadModal,
		toTop: true,
        onHide: unloadModal,
        closeClass: 'modalClose'
    });


    if (source.toLowerCase() == "facebook") {
       
 		//Call to FB api for current users feed
		//User is identified on page load, and is in a current active sessions (FB.getLoginStatus)
	   //CALLBACK RESPONSE BELOW:
	   /* FB.ApiServer._callbacks.f2e1a30c251359({
		   "data": [
		      {
		         "id": "100001015214604_115640065146500",
		         "from": {
		            "name": "Melinda Carlyle",
		            "id": "100001015214604"
		         },
		         "message": "Testing facebook",
		         "link": "http://www.facebook.com/profile.php?id=119648764712740",
		         "name": "Viva Towels Fan Page",
		         "caption": "Posted Via VivaTowels.com",
		         "icon": "http://photos-d.ak.fbcdn.net/photos-ak-sf2p/v27562/47/125342840827811/app_2_125342840827811_3306.gif",
		         "attribution": "VivaDevApp",
		         "type": "link",
		         "created_time": "2010-06-02T20:18:22+0000",
		         "updated_time": "2010-06-02T20:18:22+0000"
		      }
		   ],
		*/
        FB.api('/me/feed', { limit: 1 }, function (response) {


         

            
            var post = response.data[0];


            if (post.message) {
                //Creates a new HTML with the users info
                var newDiv = '<h2>Your Recent Activity</h2>' +
                             '<div class="fbItem">' +
                             '<a href="http://www.facebook.com/profile.php?id=' + post.from.id + '">' +
                             '<img src="https://graph.facebook.com/' + post.from.id + '/picture" /></a>' +
                             '<h3><a href="http://www.facebook.com/profile.php?id=' + post.from.id + '">' + post.from.name + '</a></h3>' +
                             '<p>' + savedPost + '</p></div>';
                //appends new HTML to div#wallPosts  
                $('#wallPosts').html(newDiv);

                //removing post cookies so user doesn't see success on refresh
                eraseCookie('socialPost');

            }

        });
		//Hides any exisiting social messages
        $('#TwitterSuccess').css('display', 'none');
		//shows new success message
        $('#FBSuccess').css('display', 'block');
    } else {


	//Twitter plugin widget for current users feed
	//socialUser is identified on page load, based on a query string value
    twitterID = socialUser;
        new TWTR.Widget({
            id: 'tweets',
            version: 2,
            type: 'profile',
            rpp: 4,
            interval: 6000,
            width: 400,
            height: 300,
            theme: {
                shell: {
                    background: '#edeafb',
                    color: '#724b8c'
                },
                tweets: {
                    background: '#fff',
                    color: '#000',
                    links: '#4aed05'
                }
            },
            features: {
                scrollbar: false,
                loop: false,
                live: false,
                hashtags: true,
                timestamp: true,
                avatars: false,
                behavior: 'all'
            }
        }).render().setUser(twitterID).start();

		//Hides any exisiting social messages
        $('#FBSuccess').css('display', 'none');
		//shows new success message
        $('#TwitterSuccess').css('display', 'block');

        //removing post cookies so user doesn't see success on refresh
        eraseCookie('socialPost');
    }
    //shows parent container and overlays

    $('#socialSuccess').jqmShow();
    $('#flashContent').hide();
}

/* *************************************************************************
=SOCIAL CLOSE (FACEBOOK AND TWITTER SUCCESS)
************************************************************************* */
function SocialClose() {
    //Hides social container and overlays
    
    $('#socialSuccess').css('display', 'none');
    $('#overlay').css('display', 'none');
}



/* *************************************************************************
=INIT MODAL WINDOWS
************************************************************************* */

function loadModal(hash){
	hash.w.show();
	if (navigator.userAgent.indexOf('MSIE 6') != -1){
		if($('#sendToFriend select').length > 0){
			$('#sendToFriend select').hide();
		}
	}
}
function unloadModal(hash){
	hash.w.hide();
	hash.o.remove();

	if ($('#flashContent').length > 0) {
	    $('#flashContent').show();
    }
	if (navigator.userAgent.indexOf('MSIE 6') != -1){
		if($('#sendToFriend select').length > 0){
			$('#sendToFriend select').show();
		}
    }
}





/* *************************************************************************
=OPEN MODALS
************************************************************************* */
function openModal(thisDiv) {
	
	//extend the object
	var activeDiv = $(thisDiv);
	
    //Init the overlay
    activeDiv.jqm({
        overlayClass: 'modalOverlay',
        onShow: loadModal,
        toTop: true,
        onHide: unloadModal,
        closeClass: 'modalClose'
    });

    activeDiv.jqmShow();
}




/* *************************************************************************
=POPULATE SOCIAL
************************************************************************* */

function populateSocial(thisString) {
    
    var messageArray = new Array();
    var n = 0;
    for (var i = 0; i < thisString.length; i++) {
        if (thisString[i] != null) {
            var type = thisString[i].Source;
            if (type == 'fb') {
                var cssClass = 'facebook';
                var postText = 'Wall Post';
            } else if (type == 'tw') {
                var cssClass = 'tweet';
                var postText = 'Tweeted';
            }
            var name = thisString[i].Name;
            var message = unescape(thisString[i].Message);
            var fullMessage = '';
            if (message.length > 50) {
                var fullMessage = message;
                message = message.substring(0, 48);
                message = message.replace(/\w+$/, '...');
            }
            var newDiv = '<div class="post ' + cssClass + '" id="position' + i + '">' +
                             '<div class="postContent">' +
                             '<h3>Post</h3><p class="showp">' + message + '</p>' +
                             '<p class="hidep">' + fullMessage + '</p>' +
                             '<span>' + name + ' <em>' + postText + '</em></span>' +
                             '</div><div class="postBottom"></div></div>';

            if (fullMessage != '') {
                messageArray[n] = 'position' + i;
                n++;
            }
            if (i <= 2) {
                $('#socialLeft').append(newDiv);
            } else {
                $('#socialRight').append(newDiv);
            }
        }
    }
    for (var c = 0; c < messageArray.length; c++) {
        $('#' + messageArray[c]).hover(
                  function () {


                      // var currentTop = parseInt($(this).css('top').replace("px", ""));
                      //$(this).attr('startTop', $(this).css('top'));

                      $(this).children('.postContent').children('.showp').hide();
                      $(this).children('.postContent').children('.hidep').show();


                      var currentBot = parseInt($(this).css('bottom').replace("px", ""));
                      var newBot = $(this).attr('startBot', $(this).css('bottom'));

                      /* var currentHeight = $(this).height();

                      if (currentTop > 0) {
                      if (currentHeight > 200) {
                      var newTop = currentTop - (currentHeight / 3);
                      } else {
                      var newTop = currentTop - (currentHeight / 4);
                      }

                      } else {
                      var newTop = -10;
                      }*/

                      //$(this).css({ 'top': newTop + 'px', 'z-index': '104' });

                      $(this).css({ 'bottom': newBot + 'px', 'z-index': '1000' });
                      $(".mainContent").css({ 'z-index': '500' });

                  },
                  function () {

                      $(this).css({ 'bottom': $(this).attr('currentBot'), 'z-index': '103' });
                      $(".mainContent").css({ 'z-index': '50' });
                      
                      $(this).children('.postContent').children('.hidep').hide();
                      $(this).children('.postContent').children('.showp').show();
                      
                  }
                );
    }

    showSocial();

}



/* *************************************************************************
=SHOW SOCIAL
************************************************************************* */
function showSocial() {
    //var topLeft = 0;
    //var topRight = 0;

    var botLeft = 108;
    var botRight = 108;

    $('#socialLeft .post').each(function (i) {

        var currentTop = $(this).height();
        $(this).css('bottom', '-' + botLeft + 'px');

        botLeft = botLeft + 148;
    });

    $('#socialRight .post').each(function (i) {

        var currentTop = $(this).height();
        $(this).css('bottom', '-' + botRight + 'px');

        botRight = botRight + 148;

    });
    q = 0;
    startPausing();
}



/* *************************************************************************
=START PAUSING
************************************************************************* */
function startPausing() {
    if (q <= 5) {
        window.setTimeout("startPausing()", 1000);
        var currentId = 'position' + q;
        if (navigator.userAgent.indexOf('MSIE') != -1) {
            $('#position' + q).show();
        } else {

            $('#position' + q).fadeIn('slow');
        }


        q++;
    }
}



/* *************************************************************************
=SET FACEBOOK COOKIE
************************************************************************* */

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}


/* *************************************************************************
Misc Form Validation functions
************************************************************************* */


function isBlank(field) {
    if (field == null || field == "") { return true; }
    return false;
}
function isValidEmail(email) {
    var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
    return filter.test(email);
}







/* *************************************************************************
=FACEBOOK AND TWITTER POSTING
************************************************************************* */
var fbName;
var q;
var twitterID;
var twitterName;

function postFB(body) {
    FB.api('/me', function (response) {
        fbName = response.name;


        var vivaLink = "http://www.facebook.com/VIVATowels";
        var vivaName = "Viva Towels Fan Page";
        var vivaDes = "Posted Via VivaTowels.com";
        var vivaIcon = "http://vivatowels.com/_images/viva.facebook.icon.small.gif";
        FB.api('/me/feed', 'post', { message: body, link: vivaLink, name: vivaName, caption: vivaDes, icon: vivaIcon, picture: vivaIcon }, function (response) {

            if (!response || response.error) {
                alert('Error occured');
            } else {
                body = escape(body);
                $.ajax({
                    type: "POST",
                    url: "shareForm.aspx/ShareFB",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: "{'Name' : '" + fbName + "', 'Message' : '" + body + "', 'Location' : 'Wall Post', 'Source' : 'fb', 'Title' : ''}",
                    success: successFB
                });
                showSuccess('Facebook')
            }

        });
    });

}
function successFB() {
}
function show_FB_auth() {
    var body = $('#facebookPost').attr("value");

    $('#socialError').jqm({
        overlayClass: 'clearOverlay',
        onShow: loadModal,
        onHide: unloadModal,
        closeClass: 'modalClose'
    });
    $('.homeError').hide();
    if (body == "") {
        $('#noMessage').show();
        $('#socialError').jqmShow();
        //alert('please enter some text to post');
        return false;
    } else if (body.length > 220) {

        $('#facebookError').show();
        $('#socialError').jqmShow();
        return false;
    }

    createCookie('socialPost', body);

    if (FBauth) {
        postFB(body);
    }
    else {
        window.open("https://graph.facebook.com/oauth/authorize?client_id=" + appID + "&type=user_agent&display=popup&scope=publish_stream,offline_access&cancel_url=http://www.facebook.com/connect/login_failure.html&redirect_uri=http://" + callbackURL + "/auth.aspx?" + body + "&", "Facebook", "menubar=0,resizable=1,width=600,height=340");
    }
}


function show_Twitter_auth() {
    var body = $('#facebookPost').attr("value");

    $('#socialError').jqm({
        overlayClass: 'clearOverlay',
        onShow: loadModal,
        onHide: unloadModal,
        closeClass: 'modalClose'
    });
    $('.homeError').hide();
    if (body == "") {
        $('#noMessage').show();
        $('#socialError').jqmShow();
        //alert('please enter some text to post');
        return false;
    } else if (body.length > 140) {

        $('#twitterError').show();
        $('#socialError').jqmShow();
        return false;
    }

    body = encodeURIComponent($('#facebookPost').attr("value"));
    createCookie('socialPost', body);
    window.open("twitter.aspx?" + body, "Twitter", "menubar=0,resizable=1,width=900,height=400");
}




function savingsRedirect() {
    $("document").ready(function () {
        if (self != top) top.location = '/savings/thank-you.aspx';
        $('.mainContentWrapper').css("display", "block");
    });
}


	
