/*!
 * mediaG.main
 * http://mediaG.com/
 *
 * Main site class
 *
 * Copyright (c) 2009-2010 Media Genesis
 *
 */
/*global window, document, jQuery, $, mediaG, swfobject, WPsettings, GBrowserIsCompatible, GMap2, GLatLng, GIcon,
  GMarker, GEvent, GSize, GPoint, G_HYBRID_MAP */
mediaG = window.mediaG || {};

(function (mediaG, $) {

    mediaG.main = function (options) {

        var self = this, // used in jQuery scope
            option; // used to loop through options
        this.popupStatus = 0; //0 means disabled; 1 means enabled
        this.currentPopup = null;

        if (options) {
            for (option in options) {
                if (this.hasOwnProperty(option)) {
                    this[option] = options[option];
                }
            }
        }

        /**
        * init
        *
        * random page formatting stuff
        **/
        this.init = function () {
            // fix png transparency in ie6
            //$(document).pngFix();

            // set up the tweet feed in the header
            if ($.fn.tweet) {
                $(".tweet").tweet({
                    username: "mediag",
                    join_text: "auto",
                    avatar_size: 32,
                    count: 1,
                    auto_join_text_default: "we said:",
                    auto_join_text_ed: "we",
                    auto_join_text_ing: "we were",
                    auto_join_text_reply: "we replied to",
                    auto_join_text_url: "we were checking out",
                    loading_text: "loading tweets...",
                    target: "_blank"
                });
            }

            // truncate content in short text areas
            // $("span.clientInfo").autoEllipsis();
            // $("#shortDescription").autoEllipsis();
            // $("#nextProject, #prevProject").autoEllipsis(); 

            // signupform validation
            if (mediaG.validate) {
                var validateSignup = new mediaG.validate();
                validateSignup.init($("#signupform"));
            }

            //POPUPS
            //$("#container").append("<div id=\"backgroundPopup\"></div>");
	$("#container").prepend("<div id=\"backgroundPopup\"></div>");
	
            
            // show the popup for client login in the header
            if (mediaG.validate) {
                var validateLogin = new mediaG.validate({
                    callback: function () {
                        self.openPopup($("#client-form"));
                    }
                });
                validateLogin.init($("#login"));
                
                $("#client-form a#client-formClose").click(function () {
                    self.closePopup();
                    return false;
                });
            }

            // show and hide the newsletter subscription form
            // on the 'bookmark'
            $("#subscribeOpen").click(function () {
                self.openPopup($("#signup"));
                return false;
            });
            $("#subscribeClose").click(function () {
                self.closePopup();
                return false;
            });

            // close popup on escape keypress
            $(document).keypress(function (e) {
                if (e.keyCode == 27 && self.popupStatus == 1) {
                    self.closePopup();
                }
            });

            // close popup on background click
            $("#backgroundPopup").click(function () {
                if (self.popupStatus == 1) {
                    self.closePopup();
                }
            });
        }; // init()

        /**
        * openPopup
        *
        * open a new popup div
        **/
        this.openPopup = function (popup) {
            if (self.popupStatus === 0 && $.scrollTo) {
                if ($(window).scrollTop() > 0) {
                    $.scrollTo(0, 0, {duration: 600});
                }
                $("#backgroundPopup").css({
                    opacity: 0.8
                }).fadeIn("slow");
                $(popup).fadeIn("slow");
                self.currentPopup = popup;
                self.popupStatus = 1;
            }
        }; // openPopup()



        /**
        * closePopup
        *
        * close the open popup
        **/
        this.closePopup = function () {
            if (self.popupStatus === 1) {
                $("#backgroundPopup").fadeOut("slow");
                $(self.currentPopup).fadeOut("slow");
                self.currentPopup = null;
                self.popupStatus = 0;
            }
        }; // closePopup()

        /**
        * homePageInit
        *
        * set up the home page stuff
        **/
        this.homePageInit = function () {
            $("#newsFeed li").hover(
                function () {
                    $(this).addClass("on").animate({
                        backgroundColor: "#ffffff"
                    }, "normal");
                },
                function () {
                    $(this).removeClass("on").animate({
                        backgroundColor: "#f5f5f5"
                    }, "normal");
                });

            // turn the newsfeed paragraphs into links
            $("#newsFeed li div.newsContent").css("cursor", "pointer").click(function () {
                var href = $(this).find("a").eq(0).attr("href");
                document.location = href;
                return false;
            });
        }; // homePageInit()

        /**
        * aboutPageInit
        *
        * set up the about page flash banner
        **/
        this.aboutPageInit = function () {
           
        }; // aboutPageInit()

        /**
        * newsPageInit
        *
        * set up the news page stuff
        **/
        this.newsPageInit = function () {
            // news section #commentform validation
            if (mediaG.validate) {
                $("#commentform .recaptcha_input_area").addClass("field").attr("style", "padding: 0;");
                $("#commentform #recaptcha_response_field").addClass("v-required");

                var validateComments = new mediaG.validate();
                validateComments.init($("#commentform"));
            }
        }; // newsPageInit()

		/**
        * careerPageInit
        *
        * set up the careers page form
        **/
        this.careerPageInit = function () {
			
		$('a.apply').click(function(e){
			var jobTitle = $(this).siblings("h2").text();
			
			self.openPopup($("#careers-form"));
			jQuery('#cform_header_display').show();
			jQuery('#cformsform').show();
			jQuery('#usermessagea').hide();
			
			//load the current list of job titles
			url = '/career_ajax_choices/?params=careers';
			$.getJSON(url, function (data) {
				var html = '';
				for (var i in data) {
					html += '<option value="' + i + '">'+data[i]+'</option>';
				}
				$("#cf_field_28").children().remove().end().append(html);
				$("#cf_field_28 option:contains(" + jobTitle + ")").attr("selected", true);
			});
			
			return false;
		});
		
		$("#careers-form a#formClose").click(function (e) {
			self.closePopup();
			return false;
		});

		// setup state drop-down
		$("#cf_field_8").change(function () {
			var country = $(this).val(),
			url = '';
			switch (country) {
				case 'United States':
					url = '/career_ajax_choices/?params=states';
					//$("#zip").addClass("v-required");
					break;
				case 'Canada':
					url = '/career_ajax_choices/?params=provinces';
					//$("#zip").addClass("v-required");
					break;
				default:
					url = '/career_ajax_choices/?params=other';
					//$("#zip").removeClass("v-required");
					break;
			}
			$.getJSON(url, function (data) {
				var html = '';
				for (var i in data) {
					html += '<option value="' + i + '">'+data[i]+'</option>';
				}
				$("#cf_field_9").children().remove().end().append(html);
			});
		});
		
		if (window.location.hash=='#usermessagea' && jQuery('#usermessagea').html() != '') {
			//load the form automatically
			self.openPopup($("#careers-form"));
			if (jQuery('#usermessagea').html() == 'Thank you for applying to MediaG!') {
				//window.location.hash='#';
				// window.scrollTo(0,0);
				// //window.scroll();
				 // setTimeout(function() {jQuery('#backgroundPopup').scrollIntoView(true)}, 3000);
				 //document.getElementById('careers-form').scrollIntoView(true);
				 jQuery('#careers-form').hide();
				setTimeout(function() {
					if ($(window).scrollTop() > 0) {
						$.scrollTo(0, 0, {duration: 600});
					}
					jQuery('#careers-form').show();
				},1000);
// hash = window.location.hash.replace( /^#/, '' );
// var node = $( '#' + hash );
// if ( node.length ) {
  // node.attr( 'id', '' );
// }
// document.location.hash = hash;
// if ( node.length ) {
  // node.attr( 'id', hash );
// }

				
// hash = window.location.hash.replace( /^#/, '' );
// var fx, node = jQuery( '#' + hash );
// if ( node.length ) {
  // fx = $( '<div></div>' )
          // .css({
              // position:'absolute',
              // visibility:'hidden',
              // top: jQuery(document).scrollTop + 'px'
          // })
          // .attr( 'id', hash )
          // .appendTo( document.body );
  // node.attr( 'id', '' );
// }
// document.location.hash = hash;
// if ( node.length ) {
  // fx.remove();
  // node.attr( 'id', hash );
// }


				
				jQuery('#cform_header_display').hide();
				jQuery('#cformsform').hide();
			} 
		}

			// // check errors if the form has been submitted
			// if ($("#careers-form input#submitted").length > 0) {
				// mediaG.careers.checkErrors();
			// }

			// // set odd rows to grey
			// $("#careers-form .field:odd").addClass("field-odd");

                        // // add listener to check errors if field changes
			// $("#careers-form input, #careers-form textarea, #careers-form select").blur(function () {
                                // $(this).addClass("v-processing");
				// mediaG.validate.checkError($(this));
                                // $(this).removeClass("v-processing");
			// });

			// // add date picker to start date field
			// $('#careers-form input#startDate').datePicker(); //.val(new Date().asString()).trigger('change');

			// mediaG.careers.swfUploadInit();
			// if ($("#resumeFile").val()) {
				// mediaG.careers.swfUploadFileReceived($("#resumeFileName").val(), $("#resumeFile").val());
			// }

			// // grab the form submit event handler
			// $("#careers-form form").submit(function (e) {
				// //return mediaG.careers.formSubmit();
				// alert('send');
			// });

			// // show the form if it has been posted
			// if ($("#careers-form form, #careers-form div").hasClass("form-posted")) {
				// mediaG.main.openPopup($("#careers-form"));
			// }
        }; // newsPageInit()
		
		
        /**
        * contactPageInit
        *
        * set up the contact page twitter, youtube, and google
        * maps sections
        **/
        this.contactPageInit = function () {
            // initialize tweets
            if ($.fn.tweet) {
                $(".recentTweets").tweet({
                    username: "mediag",
                    join_text: "auto",
                    avatar_size: 32,
                    count: 3,
                    auto_join_text_default: "we said,",
                    auto_join_text_ed: "we",
                    auto_join_text_ing: "we were",
                    auto_join_text_reply: "we replied to",
                    auto_join_text_url: "we were checking out",
                    loading_text: "loading tweets...",
                    target: "_blank"
                });
            }

            // set up google maps with an icon for media genesis
            // and a link to the directions page
            if (GBrowserIsCompatible && GMap2 && GLatLng && GIcon && GMarker && GEvent && GSize && GPoint && G_HYBRID_MAP) {
                if (GBrowserIsCompatible()) {
                    var map, posn, icon, marker;

                    //initialize a google map
                    var place = {
                        lat: 42.549871,
                        lng: -83.123395,
                        name: 'Media Genesis',
                        directions: 'http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=Media+Genesis+1441+e.+maple+rd.+suite+200+troy,+mi+48038&sll=42.613749,-83.088226&sspn=0.313302,0.727158&ie=UTF8&ei=767oSs30GI72zATFysXwCA&sig2=wLO5RaWGLnAQ_NzO22Ob8A&cd=1&cid=8763657740903619855&li=lmd&hq=Media+Genesis+1441+e.+maple+rd.+suite+200+troy,+mi+48038&hnear=&ll=42.549871,-83.123395&spn=0.009959,0.017316&z=16&iwloc=A',
                        address: '1441 E Maple Rd<br />Troy, MI 48083'
                    };

                    // set the center and add the zooming and
                    // type (e.g. satellite) controls
                    map = new GMap2(document.getElementById('map2'));
                    map.setCenter(new GLatLng(place.lat, place.lng), 8);
                    map.setMapType(G_HYBRID_MAP);

                    var customUI = map.getDefaultUI();
                    map.setUI(customUI);

                    // set the position of media genesis
                    posn = new GLatLng(place.lat, place.lng);

                    // create an icon for MG
                    icon = new GIcon();
                    icon.image = WPsettings.turl+"/style/images/map_logo.png";
                    icon.iconSize = new GSize(92, 59);
                    icon.iconAnchor = new GPoint(92 >> 1, 59 >> 1);

                    // place the marker at the position
                    marker = new GMarker(posn, {title: place.name, icon: icon, draggable: false});

                    // add an onclick event to the marker
                    GEvent.addListener(marker, 'click', function () {
                        window.open(place.directions);
                    });

                    // add the marker to the map
                    map.addOverlay(marker);
                }
            }
        }; // contactPageInit()

    }; // mediaG.main

    mediaG.main.prototype = new mediaG.main();
    mediaG.main.prototype.constructor = mediaG.main;

    window.mediaG = mediaG;

}(mediaG, jQuery));
