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);
}


function parseURL(url) {
    var a =  document.createElement('a');
    a.href = url;
    return {
        source: url,
        protocol: a.protocol.replace(':',''),
        host: a.hostname,
        port: a.port,
        query: a.search,
        params: (function(){
            var ret = {},
                seg = a.search.replace(/^\?/,'').split('&'),
                len = seg.length, i = 0, s;
            for (;i<len;i++) {
                if (!seg[i]) { continue; }
                s = seg[i].split('=');
                ret[s[0]] = s[1];
            }
            return ret;
        })(),
        file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
        hash: a.hash.replace('#',''),
        path: a.pathname.replace(/^([^\/])/,'/$1'),
        relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
        segments: a.pathname.replace(/^\//,'').split('/')
    };
}

function btnLogin() {
          
            $.ajax({
                type: "POST",
                url: "/index/ajax_login",
                cache: false,
                async: false,
                data: $("#login").serialize(),
                success: function(msg) {
                    if (msg == 'authenticated') {
						// good login!
						
						// if remember 
						remember = $('#remember').val();
						user = $('#user').val();
						pwd = $('#pwd').val();
						if(remember){
							createCookie('username',user,30);
							createCookie('pwd',pwd,30);
						}
						
						showSuccess('Welcome!');
						
						window.location.reload();
						
					} else {                                                        
					   // something went wrong
					   showError('The username or password you tried is invalid.');
					}
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    showError('Ajax Error #LG-1021 ' + errorThrown + textStatus);
					
                }
            });
			
			return false;
            
        }
		
		
		function btnLogout() {
          
            $.ajax({
                type: "POST",
                url: "/index/ajax_logout",
                cache: false,
                async: false,
                success: function(msg) {
                    showSuccess('Goodbye!');
					window.location.reload();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    showError('Ajax Error #LG-1021 ' + errorThrown + textStatus);
					
                }
            });
			
			return false;
            
        }
  	
		function btnForgot() {
          
            $.ajax({
                type: "POST",
                url: "/index/ajax_forgot",
                cache: false,
                async: false,
                data: $("#forgot").serialize(),
                success: function(msg) {
                     if (msg == 'sent') {
						// good login!
						showSuccess('Password Sent!');
						
					} else {                                                        
					   // something went wrong
					   showError('The email address you tried is invalid.');
					}
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    showError('Ajax Error #LG-1021 ' + errorThrown + textStatus);
					
                }
            });
			
			return false;
            
        }
		
       
$(function(){
			
			// checkfor username and password stored in cookie for this computer.
			var username = readCookie('username');
			var pwd = readCookie('pwd');
			if(username){
				//add to login username field.
				$('#user').val(username);
				if(pwd){
					$('#pwd').val(pwd);
				}
			}
			
				// Closable function
			$('.closable').append('<span class="closelink" title="Close"></span>');
				
			$('.closelink').click(function() {
				$(this).parent().fadeOut('600', function() { $(this).remove(); });
			});
			
			// Image actions menu
			$('ul.imageList li').hover(
				function() { $(this).find('ul').css('display', 'none').slideDown('fast').css('display', 'block'); },
				function() { $(this).find('ul').slideUp('fast'); }
			);	
			
			// AutoSuggest plugin setup		
			var data = {items: [
			{value: "21", name: "Mick Jagger"},
			{value: "43", name: "Johnny Storm"},
			{value: "46", name: "Richard Hatch"},
			{value: "54", name: "Kelly Slater"},
			{value: "55", name: "Rudy Hamilton"},
			{value: "79", name: "Michael Jordan"}
			]};
			$("input.autoSuggest").autoSuggest(data.items, {selectedItemProp: "name", searchObjProps: "name"});
			
			
			/* collapsible funciton */
			$('.collapsible').collapsible();
			
			/* Chart*/
			$('table.graph').visualize({type: 'bar',height: '100px', width: '400px'});			
						
			/* Tooltip effect for links */
			$('.tooltip-enabled a').tipsy({gravity: 's'});
			
			//table styling
			$("tr:even").addClass("alt");
			
			//tab funciton
			$("ul.tabs").tabs("div.panes > div");
			
			//superfish menu setup
        	$("ul.sf-menu").superfish({ 
        	delay:	500,
        	speed: 'fast',
            pathClass:  'current',
            animation:   {opacity:'show'}
        	});
			
			//Modal-Box
			$(".modal-box").click(function() {
      			$('#dialog').modal({overlayClose : true, 
      				position: ["25%",],
      				onClose: function (dialog) {
						dialog.data.fadeOut('fast', function () {
							dialog.container.slideUp('fast', function () {
								dialog.overlay.fadeOut('fast', function () {
									$.modal.close(); // must call this!
								});
							});
						});
			},
			onOpen: function (dialog) {
				dialog.overlay.fadeIn('fast', function () {
					dialog.container.slideDown('fast', function () {
						dialog.data.fadeIn('fast');
					});
				});
			}
		});
					return false;
      			});


$("#login-link").click(function() {
      			$('#login-box').modal({overlayClose : true, 
      				autoPosition : true,
       				containerCss : {position: 'absolute', width: '350px', height: '240px'} //iþe yaramýyor, fixed ile eziliyor!
      				});
      			});
	
 						
			//Messages Modal
      		$("#message-link").click(function() {
      			$('#messages-box').modal({overlayClose : true, 
      				containerId : 'messages-box-container',
      				overlayId: 'message-box-overlay',
      				autoPosition : false,
       				containerCss : {position: 'absolute'} //iþe yaramýyor, fixed ile eziliyor!
      				});
      			});
      	     		      		
  
			  $('.imageList a.confirm-image-delete').click(function (e) {
				e.preventDefault();
				// example of calling the confirm function
				// you must use a callback function (and paramater if there is) to perform the "yes" action
				confirm("Do you really want to delete this image?", deleteimage, $(this).attr("rel"));
				  });
				  
			   $('.confirm-link').click(function (e) {
				e.preventDefault();
							// you must use a callback function to perform the "yes" action
					confirm("You are going to : "+ this.href, this.href);
				});
			 	
				//modal image view functionality
				$('.imageList a.image-modal').click(function (e) {
					e.preventDefault();
					show_image(this.href);
				  });
				  
			});
			
		/* =======================================================================
			FUNCTIONS */
			
		/* Implementing image view for image gallery with simplemodal */
		function show_image(src) {
			$('#image-modal').find('img#modal-image')
	      		.attr("src",src);
	      		$('#image-modal').modal({
	      		containerId : 'image-container',
	      		overlayClose : true,
	      		onClose: function (dialog) {
						dialog.data.fadeOut('fast', function () {
							dialog.container.slideUp('fast', function () {
								dialog.overlay.fadeOut('fast', function () {
									$('#image-modal').find('img#modal-image')
	      								.attr("src"," ");
									$.modal.close(); // must call this!
								});
							});
						});
			},
			onOpen: function (dialog) {
				dialog.overlay.fadeIn('fast', function () {
					dialog.container.slideDown('fast', function () {
						dialog.data.fadeIn('fast');
					});
				});
			}

	      		});
		}
		
		/* Overriding Javascript's Alert Dialog */
		function alert(msg) {
			$('#alert').find('div.alert-content')
	      		.html(msg);
	      		$('#alert').modal({
				position: ["25%",],
				containerId: 'confirm-container',
				closeHTML: '<a class="button gray modal-close">OK</a>',
				onClose: function (dialog) {
						dialog.data.fadeOut('fast', function () {
							dialog.container.hide('fast', function () {
								dialog.overlay.fadeOut('fast', function () {
									$.modal.close(); // must call this!
								});
							});
						});
			},
			onOpen: function (dialog) {
				dialog.overlay.fadeIn('fast', function () {
					dialog.container.show('fast', function () {
						dialog.data.fadeIn('fast');
					});
				});
			}
	
				 });
		}
						
		//overrided confirm() func. uses jquery simplemodal
		function confirm(message, callback, param) {
			$('#confirm').modal({
			position: ["25%",],
			containerId: 'confirm-container', 
			onShow: function (dialog) {
				$('.message', dialog.data[0]).append(message);
	
				// if the user clicks "yes"
				$('.yes', dialog.data[0]).click(function () {
					// call the callback
					if ($.isFunction(callback)) {
						callback(param);
					}
					if(typeof callback == 'string')
			            {
			            	window.location.href = callback;
			            }
					// close the dialog
					$.modal.close();
						});
					},
					onClose: function (dialog) {
						dialog.data.fadeOut('fast', function () {
							dialog.container.hide('fast', function () {
								dialog.overlay.fadeOut('fast', function () {
									$.modal.close(); // must call this!
								});
							});
						});
			},
			onOpen: function (dialog) {
				dialog.overlay.fadeIn('fast', function () {
					dialog.container.show('fast', function () {
						dialog.data.fadeIn('fast');
					});
				});
			}

				});
		}	
		
		//Sample image delete function
		function deleteimage(id){
			//delete the image here with ajax/or classic way
			 $("#" + id).fadeOut('slow', function(){
			  	showSuccess("image has been deleted!");
			  	});
		}
		
				
			
		function showCustomMessage(msg)
		{
			$.notifyBar({
		    html: msg,
		    delay: 2000,
		    animationSpeed: "fast"
		  });  
		}

		
		
		function showSuccess(msg)
		{
			$.notifyBar({
		    html: msg,
		    cls: "success",
		    delay: 2000,
		    animationSpeed: "normal"
		  });  
		}

		
		
		function showError(msg)
		{
			$.notifyBar({
		    html: msg,
		    cls: "error",
		    delay: 2000,
		    animationSpeed: "normal"
		  });  
		}

	
	$(document).ready(function() {
		
		$("#logout-link").click(function() {
			btnLogout();
		});
	
		
		$('#login').submit(function(e) {
        	
			stopEvent(e);
		
		});	
		
		$('#forgot').submit(function(e) {
        	
			stopEvent(e);
			
		});	
		
		$('#login').bind('keypress', function(e) {
				if(e.keyCode==13){
						// Enter pressed... do anything here...
						
						btnLogin();
				}
		});
		
		$('#user').focus();

	});

/** Dropdown **/

$(function(){
	$("ul.sf-menu").supersubs({ 
        minWidth:    12,   // minimum width of sub-menus in em units 
        maxWidth:    27,   // maximum width of sub-menus in em units 
        extraWidth:  1     // extra width can ensure lines don't sometimes turn over 
                           // due to slight rounding differences and font-family 
	}).superfish();         
});


/** Twitter **/

$(function() {
	  /*$("#twitter").getTwitter({
		  userName: "ChargedPixels",
		  numTweets: 3,
		  loaderText: "Loading tweets...",
		  slideIn: true,
		  showHeading: true,
		  headingText: "Latest Tweets",
		  showProfileLink: true
	  });*/
});


/** Blockqoute **/

$(function() {
		$('blockquote').quovolver();
});


/** Cycle Slider 1 **/

(function($){ 
	$(function(){
		/** Add the next and previous buttons with JavaScript to gracefully degrade */
		var cycle_container = $('#slide-container');
		cycle_container.append('<div id="cycle-next"></div><div id="cycle-prev"></div>');
		cycle_start(cycle_container, 0);
		/** Restart the slideshow when someone resizes the browser to ensure that sliding distance matches the correct viewport */
		$(window).resize(function(){
			var current_slide = cycle_container.find('.slide:visible').index();
			if(window.console&&window.console.log) { console.log('current_slide'+current_slide); }
			cycle_container.cycle('destroy');
			new_window_width = $(window).width();
			cycle_container.find('.slide').width(new_window_width);
			cycle_start(cycle_container, current_slide);
		});
	});
	/** Cycle configurations */
	function cycle_start(container, index){
		var window_width = $(window).width();
		container.find('.slide').width(window_width);
		if (container.length > 0){
			container.cycle({
				timeout: 8000,
				speed: 600,
				pager: '#cycle-pager',
				slideExpr: '.slide',
				fx: 'scrollHorz',
				easeIn: 'linear',
				easeOut: 'swing',
				startingSlide: index,
				pagerAnchorBuilder: cycle_paginate
			});
		}
	}
	function cycle_paginate(ind, el) {
		return '<a href="#slide-'+ind+'"><span>'+ind+'</span></a>';
	}
})(jQuery);


/** Cycle Slider 2 **/

(function($){ 
	$(function(){
		/** Add the next and previous buttons with JavaScript to gracefully degrade */
		var cycle_container = $('#slide-container-2');
		cycle_container.append('<div id="cycle-next"></div><div id="cycle-prev"></div>');
		cycle_start(cycle_container, 0);
		/** Restart the slideshow when someone resizes the browser to ensure that sliding distance matches the correct viewport */
		$(window).resize(function(){
			var current_slide = cycle_container.find('.slide:visible').index();
			if(window.console&&window.console.log) { console.log('current_slide'+current_slide); }
			cycle_container.cycle('destroy');
			new_window_width = $(window).width();
			cycle_container.find('.slide').width(new_window_width);
			cycle_start(cycle_container, current_slide);
		});
	});
	/** Cycle configurations */
	function cycle_start(container, index){
		var window_width = $(window).width();
		container.find('.slide').width(window_width);
		if (container.length > 0){
			container.cycle({
				timeout: 8000,
				speed: 600,
				pager: '#cycle-pager',
				slideExpr: '.slide',
				fx: 'fade',
				easeIn: 'linear',
				easeOut: 'swing',
				startingSlide: index,
				pagerAnchorBuilder: cycle_paginate
			});
		}
	}
	function cycle_paginate(ind, el) {
		return '<a href="#slide-'+ind+'"><span>'+ind+'</span></a>';
	}
})(jQuery);


/** Filterable Portfolio **/

$(document).ready(function(){
	
	var items = $('#portfolio-stage li'),
		itemsByTags = {};
	
	// Looping though all the li items:
	
	items.each(function(i){
		var elem = $(this),
			tags = elem.data('tags').split(',');
		
		// Adding a data-id attribute. Required by the Quicksand plugin:
		elem.attr('data-id',i);
		
		$.each(tags,function(key,value){
			
			// Removing extra whitespace:
			value = $.trim(value);
			
			if(!(value in itemsByTags)){
				// Create an empty array to hold this item:
				itemsByTags[value] = [];
			}
			
			// Each item is added to one array per tag:
			itemsByTags[value].push(elem);
		});
		
	});

	// Creating the "Everything" option in the menu:
	createList('Everything',items);

	// Looping though the arrays in itemsByTags:
	$.each(itemsByTags,function(k,v){
		createList(k,v);
	});
	
	$('#filter a').live('click',function(e){
		var link = $(this);
		
		link.addClass('active').siblings().removeClass('active');
		
		// Using the Quicksand plugin to animate the li items.
		// It uses data('list') defined by our createList function:
		
		$('#portfolio-stage').quicksand(link.data('list').find('li'));
		e.preventDefault();
	});
	
	$('#filter a:first').click();
	
	function createList(text,items){
		
		// This is a helper function that takes the
		// text of a menu button and array of li items
		
		// Creating an empty unordered list:
		var ul = $('<ul>',{'class':'hidden'});
		
		$.each(items,function(){
			// Creating a copy of each li item
			// and adding it to the list:
			
			$(this).clone().appendTo(ul);
		});

		ul.appendTo('#portfolio');

		// Creating a menu item. The unordered list is added
		// as a data parameter (available via .data('list'):
		
		var a = $('<a>',{
			html: text,
			href:'#',
			data: {list:ul}
		}).appendTo('#filter');
	}
});


/** Contact Form 

$(document).ready(function () {
    $('form#contact-form').submit(function () {
        $('form#contact-form .error').remove();
        var hasError = false;
        $('.requiredField').each(function () {
            if (jQuery.trim($(this).val()) == '') {
                var labelText = $(this).prev('label').text();
                $(this).parent().append('<div class="error">Must enter ' + labelText + '</div>');
                $(this).addClass('inputError');
                hasError = true;
            } else if ($(this).hasClass('email')) {
                var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
                if (!emailReg.test(jQuery.trim($(this).val()))) {
                    var labelText = $(this).prev('label').text();
                    $(this).parent().append('<div class="error">Invalid ' + labelText + '</div>');
                    $(this).addClass('inputError');
                    hasError = true;
                }
            }
        });
        if (!hasError) {
            $('form#contact-form input.submit').fadeOut('normal', function () {
                $(this).parent().append('');
            });
            var formInput = $(this).serialize();
            $.post($(this).attr('action'), formInput, function (data) {
                $('form#contact-form').slideUp("fast", function () {
                    $(this).before('<div class="success">Your email was sent. We will contact you ASAP.</div>');
                });
            });
        }

        return false;

    });
});
**/

/** Pretty Hover **/

$(document).ready(function(){									
	$('.blog-post-image-wrapper').hover(
		function(){
			$(this).find('a img').animate({opacity: ".6"}, 500);		
			$(this).find('.zoom').animate({top:"-150px"}, 500);			
		}, 
		function(){
			$(this).find('a img').animate({opacity: "1.0"}, 500);					
			$(this).find('.zoom').animate({top:"85px"}, 500);
		});			
});
	

/** Pretty Photo **/

$(function() {
	$("area[rel^='prettyPhoto']").prettyPhoto();
	
	$(".gallery:first a[rel^='prettyPhoto']").prettyPhoto({animation_speed:'normal',theme:'light_square',slideshow:3000, autoplay_slideshow: false});
	$(".gallery:gt(0) a[rel^='prettyPhoto']").prettyPhoto({animation_speed:'fast',slideshow:10000, hideflash: true});

	$("#custom_content a[rel^='prettyPhoto']:first").prettyPhoto({
		custom_markup: '<div id="map_canvas" style="width:260px; height:265px"></div>',
		changepicturecallback: function(){ initialize(); }
	});

	$("#custom_content a[rel^='prettyPhoto']:last").prettyPhoto({
		custom_markup: '<div id="bsap_1259344" class="bsarocks bsap_d49a0984d0f377271ccbf01a33f2b6d6"></div><div id="bsap_1237859" class="bsarocks bsap_d49a0984d0f377271ccbf01a33f2b6d6" style="height:260px"></div><div id="bsap_1251710" class="bsarocks bsap_d49a0984d0f377271ccbf01a33f2b6d6"></div>',
		changepicturecallback: function(){ _bsap.exec(); }
	});
});


/** Accordion **/

$(function() {
	//Set default open/close settings
	$('.acc_container').hide(); //Hide/close all containers
	/*$('.acc_trigger:first').addClass('active').next().show();*/ //Add "active" class to first trigger, then show/open the immediate next container
	
	//On Click
	$('.acc_trigger').click(function(){
		if( $(this).next().is(':hidden') ) { //If immediate next container is closed...
			$('.acc_trigger').removeClass('active').next().slideUp(); //Remove all "active" state and slide up the immediate next container
			$(this).toggleClass('active').next().slideDown(); //Add "active" state to clicked trigger and slide down the immediate next container
		}
		return false; //Prevent the browser jump to the link anchor
	});
});


/** Roundabout slider **/

$(function() {
      $('ul#myRoundabout').roundabout({
		 minOpacity: 0.3, // invisible!
         minScale: 0.65, // tiny!
		 duration: 500
      });
});





