/* JW Player Setup */
var currentState = 'NONE';
var player = null;
function playerReady(thePlayer) {
    player = window.document[thePlayer.id];
    addListeners();
}
function addListeners() {
    if (player) { 
        player.addModelListener("STATE", "stateListener");
    } else {
        setTimeout("addListeners()",100);
    }
}
function stateListener(obj) { //IDLE, BUFFERING, PLAYING, PAUSED, COMPLETED
    currentState = obj.newstate;
    previousState = obj.oldstate;
    if((currentState=='COMPLETED') && (jQuery("#cinema_view").dialog("isOpen"))){
        jQuery('#cinema_view').dialog('close');
    }
    if((currentState=='COMPLETED') && (jQuery("#cinema_view-small").dialog("isOpen"))){
        jQuery('#cinema_view-small').dialog('close');
    }
    if (currentState=='PLAYING' && $.onPlayerPlaying != undefined) {
        $.onPlayerPlaying();
    }
    if (currentState=='COMPLETED' && $.onPlayerComplete != undefined) {
        $.onPlayerComplete();
    }
}
function createPlayer(webRoot, playerSkin, playerFile, playerImg, allowFs, playerId, playerDivId, playerWidth, playerHeight, flashVars) {
	//if(!FlashDetect.installed && $.browser.webkit == true && $.browser.safari == true){
		//alert("Flash is required to enjoy this site."); 
		//location.href = playerFile;
		//window.open(playerFile,"","")
	//}
	
    if (flashVars == null) {
     flashVars = {};
    } 
    flashVars = jQuery.extend({
        skin: webRoot+playerSkin,
        image: playerImg,
        file: playerFile,
        bufferlength: "2",
        abouttext: "Condor Films AG",
        aboutlink: "http://www.condorfilms.com/",
        screencolor: "#ffffff",
        autostart: "true"
    }, flashVars);
    var params = {
        menu: "false",
        allowfullscreen: allowFs,
        allowscriptaccess: "always",
        wmode: "transparent"
        //,bgcolor: "#ffffff"
    };
    var attributes = {
        id:playerId,    
        name:playerId
    };
    swfobject.embedSWF(webRoot+"_swf/player.swf", playerDivId, playerWidth, playerHeight, "9.0.115", webRoot+"_swf/expressInstall.swf", flashVars, params, attributes);
}
function createPlayerNoAutostart(webRoot, playerSkin, playerFile, playerImg, allowFs, playerId, playerDivId, playerWidth, playerHeight, flashVars) {
    if (flashVars == null) {
     flashVars = {};
    } 
    flashVars = jQuery.extend({
        skin: webRoot+playerSkin,
        image: playerImg,
        file: playerFile,
        bufferlength: "2",
        abouttext: "Condor Films AG",
        aboutlink: "http://www.condorfilms.com/",
        screencolor: "#ffffff",
        autostart: "false"
    }, flashVars);
    var params = {
        menu: "false",
        allowfullscreen: allowFs,
        allowscriptaccess: "always",
        wmode: "transparent"
        //,bgcolor: "#ffffff"
    };
    var attributes = {
        id:playerId,    
        name:playerId
    };
    swfobject.embedSWF(webRoot+"_swf/player.swf", playerDivId, playerWidth, playerHeight, "9.0.115", webRoot+"_swf/expressInstall.swf", flashVars, params, attributes);
}

function endIntro() {
  if ($('#intro').data('ended')) return;
  $('#intro').data('ended', true);
  removeCloak();
  if ($('#feature-container').data('featureClickTag')) {
    $('#feature-container').fadeIn('slow');
    $('#feature').embedFeature($('#feature-container').data('featureClickTag'));
  }
};

function removeCloak() {
  $('.cloak').fadeOut('slow', function() {
    $(this).remove();
  })
};

/* jQuery Setup */
$(document).ready(function() {
	if(!FlashDetect.installed && $.browser.webkit == true && $.browser.safari == true && $('#player-wrapper-small').length){
		$('#player-wrapper-small').css('position', 'relative');
		var tmpLeft = ($('#player-wrapper-small').width() / 2) - 9;
		var tmpTop = ($('#player-wrapper-small').height() / 2) - 17;
		$('#player-wrapper-small').append('<img src="http://www.condorfilms.com/_img/play-button.png" border="0" alt="" title="" width="19" height="20" style="position: absolute; top:'+tmpTop+'px; left:'+tmpLeft+'px;" />');
		$('#player-caption-small').css('margin-top', '-18px');
	}
	if(!FlashDetect.installed && $.browser.webkit == true && $.browser.safari == true && $('#player-wrapper').length){
		$('#player-wrapper').css('position', 'relative');
		var tmpLeft = ($('#player-wrapper').width() / 2) - 9;
		var tmpTop = ($('#player-wrapper').height() / 2) - 17;
		$('#player-wrapper').append('<img src="http://www.condorfilms.com/_img/play-button.png" border="0" alt="" title="" width="19" height="20" style="position: absolute; top:'+tmpTop+'px; left:'+tmpLeft+'px;" />');
		$('#player-caption').css('margin-top', '-18px');
	}
	if(!FlashDetect.installed && $.browser.webkit == true && $.browser.safari == true && $('#a-slot-content-31-body-2').length && $('#a-slot-content-31-body-2 .aImage img').length < 1){
		$('#a-slot-content-31-body-2 .aImage').append('<img src="http://www.condorfilms.com/_img/faro_formate.png" border="0" alt="" title="" width="480" height="330" />');
	}
	
    function showContactForm() {
        if ($('#contact-form .message').length) {
            $('#contact-form form').hide();
        }
        $('#contact-wrapper').show();
        $('#video-info-button .info').hide();
        $('#video-info-button .close').show();
        $('#recaptcha_widget_div').hide();
    }
    function hideContactForm() {
        $('#contact-wrapper').hide();
        $('#video-info-button .close').hide();
        $('#video-info-button .info').show();
        $('#contact-form .message').remove();
        $('#contact-form form').show();
    }
    $('#video-info-button .info').click(showContactForm);
    $('#video-info-button .close').click(hideContactForm);
    if ($('#contact-form .message').length) {
        showContactForm();
    } else {
        hideContactForm();
    }
    
    
    $('#contact-form input.submit').click(function(event) {
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		if (reg.test($('#contact-form #contact-email').val()) 
			&& $('#contact-form #contact-email').val() != '' 
			&& $('#contact-form #contact-name').val() != ''
			&& reg.test($('#contact-form #contact-contactemail').val())
			&& $('#contact-form #contact-contactemail').val() != '' 
			&& $('#contact-form #contact-contactname').val() != '' 
			) {
            // success
            $('#contact-form').data('submitting', true);
            $('#contact-form input.text').each(function() {
                if ($(this).val() == $(this).data('defaultVal')) {
                    $(this).val('');
                }
            });
        } else {
            alert(i18n_tipafriend_form_error_msg);
            event.preventDefault();
        }
		/*
        if (reg.test($('#contact-email').val()) && $('#contact-email').val() != '' && $('#contact-name').val() != '') {
            // success
            $('#contact-form').data('submitting', true);
            $('#contact-form input.text, #contact-form textarea').each(function() {
                if ($(this).val() == $(this).data('defaultVal')) {
                    $(this).val('');
                }
            });
        } else {
            alert('Bitte geben Sie Ihren Namen und eine gültige E-Mail-Adresse an.');
            event.preventDefault();
        }
		*/
    });
    $('#contact-form input.text, #workzone .text').focus(function(event) {
        if ($('#contact-form').data('submitting')) return;
        var defaultVal = $(this).data('defaultVal');
        if (defaultVal == undefined) {
            defaultVal = $(this).val();
            $(this).data('defaultVal', defaultVal);
        }
        if ($(this).val() == defaultVal) {
            $(this).val('');
        }
    });
    $('#contact-form input.text, #workzone .text').blur(function(event) {
        if ($(this).val() == '') {
            $(this).val($(this).data('defaultVal'));
        }
    });
    $('#contact-form-closer').click(function() {
        $('#contact-wrapper').hide();
    });
	
	/* END CONTACT **************************************/
	
	

    var intro = $('#teaser');
    if (intro.length > 0) {
        var intro = $('#teaser');
        var introHeight = intro.height();
        var introOffset = intro.offset();
        var bottomCloak = $('<div class="cloak">&nbsp;</div>');
        var topCloak = $('<div class="cloak">&nbsp;</div>');
        $('body').append(topCloak, bottomCloak);
        bottomCloak.width($(window).width());
        bottomCloak.height($(window).height() - introOffset.top - introHeight);
        //bottomCloak.offset({'left': 0, 'top': Math.ceil(introOffset.top + introHeight)});
        bottomCloak.css('top', Math.ceil(introOffset.top + introHeight)+'px')
        topCloak.width($(window).width());
        topCloak.height(introOffset.top);

        /*
        // IE triggert mousemove event beim Laden der Seite, auch wenn der Cursor nur über der Seite schwebt.
        // Der Handler unten löst das Problem, indem er die effektiven Pixel der Bewegung überprüft. 
        $(document).mousemove(function() {
        removeCloak();
        });
        */
        $(document).mousemove(function(event) {
            var prevClientXY = $(document).data('prevClientXY');
            if (prevClientXY != null && Math.abs(event.clientX - prevClientXY[0]) + Math.abs(event.clientY - prevClientXY[1]) > 0) {
                removeCloak();
            }
            $(document).data('prevClientXY', [event.clientX, event.clientY]);
        });

        $(window).keydown(function() {
            removeCloak();
        });

        var params = {
            allowScriptAccess: 'always'
            ,wmode: 'transparent'
        };

        $.fn.embedFeature = function(url) 
        {
            var flashVars = {
                clickTag: url
            };
            swfobject.embedSWF('http://www.condorfilms.com/uploads/extra/bba_feature.swf', $(this).attr('id'), $(this).width(), $(this).height(), "9.0.115", "http://www.condorfilms.com/_swf/expressInstall.swf", flashVars, params, {});
        }

        var flashVars = {};
        swfobject.embedSWF(intro.find('link[rel=teaser-swf]').attr('href'), 'teaser', intro.width(), intro.height(), "9.0.115", "http://www.condorfilms.com/_swf/expressInstall.swf", flashVars, params, {});

        // Unsichtbare Teile hinter cloak-divs einblenden. Wären diese früher sichtbar gewesen, hätten sie in verschiedenen Browsern kurz aufgeblitzt. 
        $('#header *, #news, #footer, #mainnav, #hr-header, #hr-teaser, #teaser img').css('visibility', 'visible');

        if (swfobject.getFlashPlayerVersion().major == 0) {
            endIntro();
        }  
    }
    
	
	
	
	// Play Showreel
    if ($('#showreel').length) {
		// Since in IE the video player is not initialized when hidden, it is not hidden, but covered with a div.cloak, 
		// and moved to the background via CSS. The cloak is hidden for playing the video. 
		
		if(location.hash.slice(1) == 'showreel'){
			if(!FlashDetect.installed && $.browser.webkit == true && $.browser.safari == true && $('#player-wrapper #player a').attr('href')){
				location.href = $('#player-wrapper #player a').attr('href');
			}
	
            $('#overview-list').hide();
            $('#news').hide();
            $('#get-fit').hide();
            $('#showreel').show();
			initPlayer();
			
			$('.player-closer a').click(function() {
				location.hash = '';
				location.reload(true);
			});
			return false;
		}
		
		
        $('#play-showreel').click(function() {
			location.hash = 'showreel';
            $('#overview-list').hide();
            $('#news').hide();
            $('#get-fit').hide();
            $('#showreel').show();
			return false;
		});
		
        $('.player-closer a').click(function() {
			location.hash = '';
            $('#player1')[0].sendEvent('STOP');
            $('#overview-list').show();
            $('#news').show();
            $('#get-fit').show();
            $('#showreel').hide();
            return false;
        });
    }
    
    $.fn.replaceHeaderLink = function() {
        $(this).find('.tit').each(function() {
            var repl = $('<span>'+$(this).html()+'</span>');
            repl.attr('class', $(this).attr('class'));
            repl.data('replaced', $(this));
            $(this).replaceWith(repl);
			var deviceAgent = navigator.userAgent.toLowerCase();
			var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
			if(agentID){
				  $(this).css('font-size', '0.6em');
			}
        });
    };
    
    $.fn.restoreHeaderLink = function() {
        $(this).find('.tit').each(function() {
            if ($(this).data('replaced')) {
                $(this).replaceWith($(this).data('replaced'));
            }
			var deviceAgent = navigator.userAgent.toLowerCase();
			var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
			if(agentID){
				  $(this).css('font-size', '0.6em');
			}
        });
    };

    // Fade .hi in, .lo out on mouseenter

	$('#overview li').mouseenter(function() {
        $(this).find('.hi').each(function() {
            if ($(this).hasClass('no-fade')) return;
			var initial = $(this).data('initialOpacity');
			if (initial == null) {
				initial = $(this).css('opacity');
				$(this).data('initialOpacity', initial);
			}
			$(this).css('opacity', 0);
			$(this).show();
            $(this).fadeTo('fast', initial);
        });
        $(this).find('.lo').each(function() {
            if ($(this).hasClass('no-fade')) return;
            $(this).show();
            $(this).fadeOut('fast');
        });
    });

    // Fade .hi out, .lo in on mouseleave
    $('#overview a').mouseleave(function() {
        $(this).find('.hi').each(function() {
            if ($(this).hasClass('no-fade')) return;
            $(this).show();
            $(this).fadeOut('fast');
        });
        $(this).find('.lo').each(function() {
            if ($(this).hasClass('no-fade')) return;
            $(this).hide();
            $(this).fadeIn('fast');
        });
    });
    
    $('.accordion').accordion({
        autoHeight: false
        ,changestart: function(event, ui) {
            ui.oldHeader.restoreHeaderLink();
            ui.newHeader.replaceHeaderLink();
        }
    });
    
    $('.accordion').find('.tit:first').each(function() {
        $(this).closest('h1, h2').replaceHeaderLink();
    });

    if (jQuery.fn.jcarousel) {
        var initCallback = function(carousel)
        {
			if ((navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('iPod') != -1) || (navigator.userAgent.indexOf('iPad') != -1)){
				carousel.buttonPrev.html('<a href="#" title="'+i18n_zurueck+'">'+i18n_zurueck+'&nbsp;</a>&#124;&nbsp;');
			}else{
				carousel.buttonPrev.html('<a href="#" title="'+i18n_zurueck+'">'+i18n_zurueck+'&nbsp;</a>&#124;');
			}
			carousel.buttonNext.html('<a href="#" title="'+i18n_weiter+'">&nbsp;'+i18n_weiter+'</a>');
			
            carousel.buttonNext.bind('click', function() {
                    carousel.options.auto = false;
            });
            carousel.buttonPrev.bind('click', function() {
                    carousel.options.auto = false;
            });
            $('#matrix_carousel').mouseenter(function() {
                carousel.options.auto = false;
            });
			
			$('#gs-subnav-downloads li a').click(function(){
                carousel.options.auto = false;
				//carousel.stopAuto();
				return false;
			});
			
			if(location.hash == '#portrait' || location.hash == '#history' || location.hash == '#filmografie' || location.hash == '#awards'){
                carousel.options.auto = false;
				//$(location.hash+'-downloads').trigger('click');
				//carousel.stopAuto();
				return false;
			}
        }
        var matrixClassName = $('#matrix_carousel').attr('class');
        if (matrixClassName != undefined) {
            var rx = /([0-9])x\1/;
            var matrixSize = parseInt(rx.exec(matrixClassName)[1]);
            jQuery('#matrix_carousel').jcarousel({
                //auto: (matrixSize == 6 ? 5 : false),
                scroll: matrixSize,
                initCallback: initCallback
            });
        }

        jQuery('#category_carousel').jcarousel({
            auto: 5,
            scroll: 1,
            //wrap:'circular',
            initCallback: initCallback
        });
        jQuery('#category_carousel_sub').jcarousel({
            //auto: 5,
            scroll: 1,
            //wrap: 'circular',
            initCallback: initCallback
        });
        jQuery('#team_carousel').jcarousel({
            auto: 5,
            scroll: 1,
            wrap:'circular',
            initCallback: initCallback
        });
		

        jQuery('#news_carousel').jcarousel({
            auto: false,
            scroll: 1,
            initCallback: initCallback
        });

        jQuery('.jcarousel-skin-cc li a img').fadeIn(600);
        jQuery('.jcarousel-skin-cc li a span').each(function() {
            if (!$(this).hasClass('inactive')) {
                $(this).fadeIn(600);
            }
        });
    }

    jQuery('.news-expand').click(function() {
        $('#news .collapsed').each(function() {
            $(this).addClass('expanded');
            $(this).removeClass('collapsed');
        });
        $('.news-collapse').show();
        $(this).hide();
        return false;
    });
    jQuery('.news-collapse').click(function() {
        $('#news .ui-accordion-header:first').trigger('click');
        $('#news .expanded').each(function() {
            $(this).addClass('collapsed');
            $(this).removeClass('expanded');
        });
        $('.news-expand').show();
        $(this).hide();
        return false;
    });

    jQuery("#cinema_view").dialog({
        autoOpen:false,
        draggable:false,
        modal:true,
        resizable:false,
        width:1024,
        height:595
    });
    
    jQuery("#cinema_view-small").dialog({
        autoOpen:false,
        draggable:false,
        modal:true,
        resizable:false,
        width:768,
        height:595
    });
    
    jQuery(window).resize(function(){
        jQuery("#cinema_view").dialog("option","position",jQuery("#cinema_view").dialog("option","position","center"));
        jQuery("#cinema_view-small").dialog("option","position",jQuery("#cinema_view-small").dialog("option","position","center"));
    });
    
    $('.fuoc').css('visibility', 'visible');

	var deviceAgent = navigator.userAgent.toLowerCase();
	var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
	if(agentID){
		jQuery('#news span.tit,#news a.tit').css('font-size', '0.6em');
		jQuery('#news .textblock').css('font-size', '1.2em');
		window.onscroll = function(){
			jQuery('#footer').css('top', (window.pageYOffset + window.innerHeight - 48) + 'px');
		};
	}
	
	
	
	//var videosFarotvA = $('#videos-farotv #player-caption-small').html();
	$('#videos-farotv #player-caption-small').html('<a id="cinema-open" class="right cinema" href="#">CINEMA</a>');
	
	
	/* HTML Files in iFrames anzeigen ********************************************************************************************************************/
	if(location.hash == '#portrait' || location.hash == '#history' || location.hash == '#filmografie' || location.hash == '#awards'){
		loadiframedata(location.hash);
	}
	$('#gs-subnav-downloads li a').click(function(){
		if (self.location.search.indexOf("=") > -1){
			var parameterArray = location.href.split("?");
			parameterArray = parameterArray[0].split("#");			
			window.location.href = parameterArray[0] + '#'+$(this).attr('rel');
		}else{
			loadiframedata('#'+$(this).attr('rel'));
		}
		return false;
	});
	/* HTML Files in iFrames anzeigen ********************************************************************************************************************/
});

/* HTML Files in iFrames anzeigen ********************************************************************************************************************/


function loadiframedata(obj){
	x = location.hash;
	//location.hash = $(obj).attr('id');
	location.hash = $(obj+'-downloads').attr('rel');
	//$('title').val($(obj).attr('rel') + ' – Condor Films');

    document.title = $(obj+'-downloads').attr('rel').replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } ) + ' – Condor Films'; 
	
	var url = $(obj+'-downloads').attr('href');
	/* SET OFF IF LIVE PAGE */
	//url = url.replace("http://www.condorfilms.com/", "http://square.selfip.biz/condorfilms.ch/");
	
	$('a').removeClass('active');
	$(obj+'-downloads').addClass('active');
	
	
	
	$("#content").empty();
	
	
	//$("#content").prepend('<iframe name="iframeSubnavDownloads" id="iframeSubnavDownloads" class="autoHeight" width="500" frameborder="0" src="'+url+'" scrolling="no"></iframe>');
	$("#content").html('<iframe name="iframeSubnavDownloads" id="iframeSubnavDownloads" class="autoHeight" width="500" frameborder="0" src="'+url+'" scrolling="no"></iframe>');
	
	$('iframe#iframeSubnavDownloads').css('visibility', 'hidden');
	
	$('iframe#iframeSubnavDownloads').load(function() {
		/*
		var elementToRemove 		= 'div#content table, div#content p, div#content table, table';
		var elementToNotRemove 		= '.content, .content table, .content p, .content h3';
		var elementToSetWidth 		= 'table, table.content, div#content table.content';
		
		$(this).contents().find(elementToRemove).not(elementToNotRemove).remove();
		$(this).contents().find(elementToSetWidth).css('width', '350px');
		
		
		
		$(this).contents().find(elementToSetWidth).css('width', 'auto');
		$(this).contents().find(elementToSetWidth).attr('width', '');
		
		
		$(this).contents().find('table.content, div#content').css('width', '450px');
		
		
		$(this).contents().find('table.content td').attr('width', '');
		
		$(this).contents().find('table.content td.Jahr').css('width', '1px');
		$(this).contents().find('table.content td.Jahr').attr('width', '1');
		
		$(this).contents().find('table.content td.Film').css('width', '410px');
		$(this).contents().find('table.content td.Film').attr('width', '410');
		
		
		$(this).contents().find('table.content').css('margin', '0px');
		$(this).contents().find('table.content, .border1').css('border', '0px');
		
		
		$(this).contents().find('img').each(function(){
			if($(this).attr('src') == 'header.jpg'){
				$(this).remove();
			}
			if($(this).width() > 460){
				$(this).width(460);
			}
		});
		
		$(this).contents().find('td.Film img').each(function(){
			if($(this).width() > 350){
				$(this).width(350);
			}
		});
		*/
		
		doIframe();
		
		$('iframe#iframeSubnavDownloads').css('visibility', 'visible');
	});
}


function doIframe(){
	o = document.getElementsByTagName('iframe');
	for(i=0;i<o.length;i++){
		if (/\bautoHeight\b/.test(o[i].className)){
			setHeight(o[i]);
			addEvent(o[i],'load', doIframe);
		}
	}
}

function setHeight(e){
	if(e.contentDocument){
		e.height = e.contentDocument.body.offsetHeight + 35;
	} else {
		e.height = e.contentWindow.document.body.scrollHeight;
	}
}

function addEvent(obj, evType, fn){
	if(obj.addEventListener)
	{
	obj.addEventListener(evType, fn,false);
	return true;
	} else if (obj.attachEvent){
	var r = obj.attachEvent("on"+evType, fn);
	return r;
	} else {
	return false;
	}
}
/* HTML Files in iFrames anzeigen ********************************************************************************************************************/
