/* 
 * Template Name: Doma
 * Created date: 2010.11.5
 * Author: Olziibat
 * Mail: olziinaa@gmail.com
 */


jQuery(document).ready(function() {

    // STYLE SWITCH FUNCTION
    jQuery('.styleswitch').click(function()
    {
        switchStylestyle(this.getAttribute("rel"));
        Cufon.refresh();
        return false;
    });
    var c = readCookie('style');
    if (c) {
        switchStylestyle(c);
        Cufon.refresh();
    }
    
    // JCYCLE SLIDESHOW FUNTION
    jQuery('.jcycle-slideshow').cycle({
        });

    // JCYCLE PAGER FUNCTION
    jQuery(function() {
        jQuery('#jcycle-slideshow').after('<div id="jcycle-pager" class="jcycle-pager">').cycle({
            pager:  '#jcycle-pager',
            before: function() {
                //if (window.console) console.log(this.src);
            }
        });
    });

    // JQUERY SPOTLIGHT FUNTION
    jQuery('.spotlight').bind('mouseover', function () {
//        $(this).spotlight({
//            exitEvent: 'mouseover',
//            speed: 100
//        });
    });

    // NIVO SLIDER FUNCTION
    jQuery('.nivo-slideshow').nivoSlider(
    {
        effect:'random', //Specify sets like: 'fold,fade,sliceDown'
        slices:15,
        animSpeed:500, //Slide transition speed
        pauseTime:3000,
        startSlide:0, //Set starting Slide (0 index)
        directionNav:true, //Next & Prev
        directionNavHide:true, //Only show on hover
        controlNav:true, //1,2,3...
        controlNavThumbs:false, //Use thumbnails for Control Nav
        controlNavThumbsFromRel:true, //Use image rel for thumbs
        controlNavThumbsSearch: '.jpg', //Replace this with...
        controlNavThumbsReplace: '_thumb.jpg', //...this in thumb Image src
        keyboardNav:true, //Use left & right arrows
        pauseOnHover:true, //Stop animation while hovering
        manualAdvance:false, //Force manual transitions
        captionOpacity:0.6, //Universal caption opacity
        beforeChange: function(){},
        afterChange: function(){},
        slideshowEnd: function(){}, //Triggers after all slides have been shown
        lastSlide: function(){}, //Triggers when last slide is shown
        afterLoad: function(){} //Triggers when slider has loaded
    }
    );

    // KWICK SLIDER FUNCTION
    jQuery('#kwicks').kwicks({
        duration: 200,
        easing: 'linear',
        max: 650,
        autoplay: true
    });

    // ROUND ABOUT SLIDER FUNCTION
    jQuery('ul#roundabout').roundabout(
    {
        easing: 'swing',
        duration: 500,
        startingChild: 0,
        shape: 'figure8'

    });

    // ROUND ABOUT SLIDER AUTOPLAY FUNTION
    var interval;

    jQuery('ul#roundabout').hover(
        function() {
            // oh no, it's the cops!
            clearInterval(interval);
        },
        function() {
            // false alarm: PARTY!
            interval = startAutoPlay();
        }
        );

    // let's get this party started
    interval = startAutoPlay();

    function startAutoPlay() {
        return setInterval(function() {
            jQuery('ul#roundabout').roundabout_animateToPreviousChild(500, 'swing');
        }, 5000);
    };

    // IMAGE OVERLAY FUNCTION
    imgIconOverlay(jQuery);

    // JQUERY UI FUNCTIONS

    // JQUERY UI ACCORDION
    jQuery( "#accordion" ).accordion({
        autoHeight: false
    });

    // JQUERY UI TABS
    jQuery( "#tabs" ).tabs({
        fx: {
            height: '100%',
            opacity: 'toggle',
            duration: 'fast'
        }
    });

    // JQUERY TOGGLE FUNTION
    jQuery(".toggle_title").toggle(
        function(){
            jQuery(this).addClass('toggle_active');
            jQuery(this).siblings('.toggle_content').slideDown("fast");
        },
        function(){
            jQuery(this).removeClass('toggle_active');
            jQuery(this).siblings('.toggle_content').slideUp("fast");
        }
        );

    
    // IMAGE PRELOADER FUNCTIONS
    jQuery('.preload').preloadImages({
        showSpeed: 1000,   // length of fade-in animation, 500 is default
        easing: 'easeOutQuad'   // optional easing, if you don't have any easing scripts - delete this option
    });
    
    // SUPER FISH MENU FUNCTION
    jQuery(function(){
        jQuery('#menu-list').superfish();
    });

    // TOOL TIP FUNCTION
    if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 7) {
    // IE 6 sucks so the effect doesn't work at all and that's why we skip it here
    // we coluld do something different for IE 6 in this area if we wanted
    }
    else {
        jQuery(function(){
            jQuery(".tool-tip").tipTip();
        });
    };

    // PORTFOLIO FILTER FUNCTION
    jQuery('#portfolio-list').filterable();

    //$("#contact-form").validationEngine();
    
    // FANCYBOX FUNCTIONS
    // -------------------------------------------------------------------


    jQuery('a[href$="#popup"]').addClass('zoom').each( function() {
        jQuery(this).attr('href', this.href.replace('#popup',''));
    });

    // FANCYBOX FOR YOUTUBE
    jQuery("a.zoom[href*='http://www.youtube.com/watch?']").each( function() {
        jQuery(this).addClass('fancyYouTube').removeClass('zoom');
    });

    // FANCYBOX FOR VIMEO
    jQuery("a.zoom[href*='http://www.vimeo.com/']").each( function() {
        jQuery(this).addClass('fancyVimeo').removeClass('zoom');
    });

    var overlayColor = '#000000';
    
    // FANCYBOX DEFAULT
    jQuery('a.zoom').fancybox({
        'titlePosition': 'outside',
        'overlayOpacity': 0.9,
        'overlayColor': overlayColor
    });

    // YOUTUBE
    jQuery('a.fancyYouTube').click(function() {
        jQuery.fancybox({
            'overlayOpacity': 0.9,
            'overlayColor': overlayColor,
            'title': this.title,
            'href': this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
            'type': 'swf',
            'titlePosition': 'outside',
            'swf': {
                'wmode': 'transparent',
                'allowfullscreen'	: 'true'
            } // <-- flashvars
        });
        return false;
    });

    // VIMEO
    jQuery("a.fancyVimeo").click(function() {
        jQuery.fancybox({
            'overlayOpacity': 0.9,
            'overlayColor': overlayColor,
            'title': this.title,
            'href': this.href.replace(new RegExp("([0-9])","i"),'moogaloop.swf?clip_id=$1'),
            'titlePosition': 'outside',
            'type': 'swf'
        });
        return false;
    });
});

// IMAGE PRELOADER

(function($){
    $.fn.preloadImages = function(options){

        var defaults = {
            showSpeed: 'fast',
            easing: 'easeOutQuad'
        };

        var options = $.extend(defaults, options);

        return this.each(function(){
            var container = $(this);
            var image = container.find('img');

            $(image).css({
                "visibility": "hidden",
                "opacity": "0"
            });
            $(image).bind('load error', function(){
                $(this).css({
                    "visibility": "visible"
                }).animate({
                    opacity:"1"
                }, {
                    duration:options.showSpeed,
                    easing:options.easing
                }).parent(container).removeClass('preload');
            }).each(function(){
                if(this.complete || ($.browser.msie && parseInt($.browser.version) == 6)) {
                    $(this).trigger('load');
                }
            });
        });
    }
})(jQuery);


// IMAGE OVERLAY

function imgIconOverlay($) {


    // This will select the items which should include the image overlays
    $("a.imgMedium:not(.noIcon)").each(function(){
        var	ctnr = $(this);
        // insert the overlay image
        if (ctnr.children('img')) {
            if (ctnr.hasClass('iconPlay')) {
                ctnr.children('img').after($('<div class="imgOverlay symbolPlay"></div>'));
            } else if  (ctnr.hasClass('iconDoc')) {
                ctnr.children('img').after($('<div class="imgOverlay symbolDoc"></div>'));
            } else {
                ctnr.children('img').after($('<div class="imgOverlay symbolZoom"></div>'));
            }
        }

        var overImg = ctnr.children('.imgOverlay');

        if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 6) {
            // IE sucks at fading PNG's with gradients so just use show hide
            overImg.css('visibility','hidden'); // not visible to start

            ctnr.hoverIntent(
                function(){
                    overImg.css('visibility','visible');
                },		// mouseover
                function(){
                    overImg.css('visibility','hidden');
                }		// mouseout
                );
        } else {
            // make sure it's not visible to start
            overImg.css('opacity',0);

            ctnr.hoverIntent(
                function(){
                    overImg.animate({
                        'opacity':'1'
                    },100,'swing');
                },		// mouseover
                function(){
                    overImg.animate({
                        'opacity':'0'
                    },100,'swing');
                }		// mouseout
                );
        }
    });
}


// STYLE SWITCH FUNCTIONS

function switchStylestyle(styleName)
{
    jQuery('link[@rel*=style][title]').each(function(i)
    {
        this.disabled = true;
        if (this.getAttribute('title') == styleName) this.disabled = false;
    });
    createCookie('style', styleName, 365);
}

// cookie functions http://www.quirksmode.org/js/cookies.html
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);
}




// SEARCH FORM SUBMIT

function submitSearch(path, params, method) {
	function get_radio_value()
	{
	for (var i=0; i < document.searchform.searchGroup1.length; i++)
	   {
	   if (document.searchform.searchGroup1[i].checked)
		  {
		  var rad_val = document.searchform.searchGroup1[i].value;
		  var search_val = document.searchform.search_field.value;
		  var form = document.createElement("form");
		  if (rad_val == "blog") {
				var path = "http://blog.footagesearch.com/";
				 method = method || "get";
				 var search_field = document.createElement("input");
				search_field.setAttribute("type", "hidden");
				search_field.setAttribute("name", "s");
				search_field.setAttribute("value", search_val);
				form.appendChild(search_field);
			} else if (rad_val == "clips") {
				var path = "http://blog.footagesearch.com/search_clips/";
				 method = method || "get";
				 var search_field = document.createElement("input");
				search_field.setAttribute("type", "hidden");
				search_field.setAttribute("name", "s");
				search_field.setAttribute("value", search_val);
				form.appendChild(search_field);
			}
			form.setAttribute("method", method);
			form.setAttribute("action", path);
			/*
			for(var key in params) {
				var hiddenField = document.createElement("input");
				hiddenField.setAttribute("type", "hidden");
				hiddenField.setAttribute("name", key);
				hiddenField.setAttribute("value", params[key]);
		
				form.appendChild(hiddenField);
			}*/
			document.body.appendChild(form); 
		   form.submit();
		  }
	   }
	}
	get_radio_value();
}


// ON ENTER LISTENER
function enterListener(event)
{
    if (event.keyCode==13)
    {
		//alert ("enter key");
	   //submitSearch();
	   setTimeout(function() {submitSearch();},200);
	 //  setTimeout(function() {alert("Delayed");},500);
	   return false;
    } else {
		return true;
	}
}
