/************************************************************************************************************
	@fileoverview
	Floating window

	Copyright (C) 2006  Alf Magne Kalleland(post@dhtmlgoodies.com)

	This library is free software; you can redistribute it and/or
	modify it under the terms of the GNU Lesser General Public
	License as published by the Free Software Foundation; either
	version 2.1 of the License, or (at your option) any later version.

	This library is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
	Lesser General Public License for more details.

	You should have received a copy of the GNU Lesser General Public
	License along with this library; if not, write to the Free Software
	Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA


	www.dhtmlgoodies.com
	Alf Magne Kalleland


Update log:

	January 18th, 2006: Added feature that makes the window cover selectboxes(ref. problem with windowed and window less elements).
	January 29th, 2006: Fixed problem showing the windows in Opera
	Feb, 8th 2006:		Added support for creating new windows dynamically
	March,	11th, 2006: Added support for getting content from external files by use of Ajax


************************************************************************************************************/

	var readSizeFromCookie = false;	// Determines if size and position of windows should be set/retreved by use of cookie
	var windowMinSize = [80,30];	// Mininum width and height of windows.

	var moveCounter = -1;
	var startEventPos = new Array();
	var startPosWindow = new Array();
	var startWindowSize = new Array();
	var initResizeCounter = -1;
	var activeWindow = false;
	var activeWindowContent = false;
	var windowSizeArray = new Array();
	var windowPositionArray = new Array();
	var currentZIndex = 10000;
	var windowStateArray = new Array();	// Minimized or maximized
	var activeWindowIframe = false;
	var divCounter = 0;
	var zIndexSet = false;

	var MSIEWIN = (navigator.userAgent.indexOf('MSIE')>=0 && navigator.userAgent.indexOf('Win')>=0 && navigator.userAgent.toLowerCase().indexOf('opera')<0)?true:false;
	var opera = navigator.userAgent.toLowerCase().indexOf('opera')>=0?true:false;

	var ajaxObjects = new Array();




	/*
	These cookie functions are downloaded from
	http://www.mach5.com/support/analyzer/manual/html/General/CookiesJavaScript.htm
	*/
	function Get_Cookie(name) {
	   var start = document.cookie.indexOf(name+"=");
	   var len = start+name.length+1;
	   if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
	   if (start == -1) return null;
	   var end = document.cookie.indexOf(";",len);
	   if (end == -1) end = document.cookie.length;
	   return unescape(document.cookie.substring(len,end));
	}
	// This function has been slightly modified
    // the 'path' parameter is ignored and it hardcodes the path to the root (i.e. "/")
    function Set_Cookie(name,value,expires,path,domain,secure) {
		expires = expires * 60*60*24*1000;
		var today = new Date();
		var expires_date = new Date( today.getTime() + (expires) );
	    var cookieString = name + "=" +escape(value) +
	       ( (expires) ? ";expires=" + expires_date.toGMTString() : "") +
           ";path=/" +
	       ( (domain) ? ";domain=" + domain : "") +
	       ( (secure) ? ";secure" : "");
	    document.cookie = cookieString;
	}

	function hideWindow()
	{
			switchElement(false,document.getElementById('dhtml_goodies_id' + this.id.replace(/[^\d]/g,'')));
	        // make sure that the active window has been set to something before setting the style
	        // if it still has the default value of 'false', then this code won't execute
	        if (activeWindow){
	            activeWindow.style.display='none';
	        }
    	}

	function startResizeWindow()
	{
		if(initResizeCounter>=0 && initResizeCounter<=10){
			initResizeCounter++;
			setTimeout('startResizeWindow()',5);
		}
	}

	function initResizeWindow(e)
	{
		if(document.all)e = event;
		initResizeCounter = 0;
		switchElement(false,document.getElementById('dhtml_goodies_id' + this.id.replace(/[^\d]/g,'')));

		startWindowSize = [activeWindowContent.offsetWidth,activeWindowContent.offsetHeight];
		startEventPos = [e.clientX,e.clientY];

		if(MSIEWIN)activeWindowIframe = activeWindow.getElementsByTagName('IFRAME')[0];
		startResizeWindow();
		return false;

	}

    function initMove(e)
	{
		if(document.all)e = event;
		moveCounter = 0;
		switchElement(false,this);
		startEventPos = [e.clientX,e.clientY];
		startPosWindow = [activeWindow.offsetLeft,activeWindow.offsetTop];
		startMove();
		if(!MSIEWIN)return false;

	}

	function stopMove(e)
	{
		if(document.all)e = event;
		moveCounter=-1;
		initResizeCounter=-1;
		if(!activeWindow || !activeWindowContent)return;
		var state = '0';
		if(windowStateArray[activeWindow.id.replace(/[^0-9]/g,'')])state = '1';

		Set_Cookie(activeWindow.id + '_attr',activeWindow.style.left.replace('px','') + ',' + activeWindow.style.top.replace('px','') + ',' + activeWindow.style.width.replace('px','') + ',' + activeWindowContent.style.height.replace('px','') + ',' + activeWindow.style.zIndex + ',' + state,50);
	}

    function startMove()
	{
		if(moveCounter>=0 && moveCounter<=10){
			moveCounter++;
			setTimeout('startMove()',5);
		}
	}

	function cancelEvent()
	{
		return (moveCounter==-1 && initResizeCounter==-1)?true:false;
	}

	function moveWindow(e)
	{

		if(document.all){
            e = event;
        }

        if( moveCounter >= 10){
			activeWindow.style.left = startPosWindow[0] + e.clientX - startEventPos[0]  + 'px';
			activeWindow.style.top = startPosWindow[1] + e.clientY - startEventPos[1]  + 'px';

		}

		if(initResizeCounter>=10){
			var newWidth = Math.max(windowMinSize[0],startWindowSize[0] + e.clientX - startEventPos[0]);
			var newHeight = Math.max(windowMinSize[1],startWindowSize[1] + e.clientY - startEventPos[1]);
			activeWindow.style.width =  newWidth + 'px';
			activeWindowContent.style.height = newHeight  + 'px';

			if(MSIEWIN && activeWindowIframe){
				activeWindowIframe.style.width = (newWidth) + 'px';
				activeWindowIframe.style.height = (newHeight+20) + 'px';
			}


		}

        	if(!document.all){
            		return false;
        	}
	}

    function initWindows(e,divObj)
    {


        var divs = document.getElementsByTagName('DIV');

        if(divObj){
            var tmpDivs = divObj.getElementsByTagName('DIV');
            var divs = new Array();
            divs[divs.length] = divObj;

            for(var no=0;no<tmpDivs.length;no++){
                divs[divs.length] = tmpDivs[no];
            }
        }

        // register the 'onclick' handler for the closeWindowLink to be the function
        // to hide the window
        var tempAnchors = document.getElementsByTagName('A');

        for (var count=0;count<tempAnchors.length;count++){
            if (tempAnchors[count].className='closeWindowLink2'){
                tempAnchors[count].onclick=hideWindow;
            }
        }

        for(var no=0;no<divs.length;no++){

            if(divs[no].className=='dhtmlgoodies_window'){

                if(MSIEWIN){
                    var iframe = document.createElement('IFRAME');
                    iframe.style.border='0px';
                    iframe.frameborder=0;
                    iframe.style.position = 'absolute';
                    iframe.style.backgroundColor = '#FFFFFF';
                    iframe.style.top = '0px';
                    iframe.style.left = '0px';
                    iframe.style.zIndex = 100;


                    var subDiv = divs[no].getElementsByTagName('DIV')[0];
                    divs[no].insertBefore(iframe,subDiv);

                }
                if(divObj){
                    divs[no].style.zIndex = currentZIndex;
                    currentZIndex = currentZIndex /1 + 1;
                }

                divCounter = divCounter + 1;
                if(divCounter==1)activeWindow = divs[no];
                divs[no].id = 'dhtml_goodies_id' + divCounter;
                divs[no].onmousedown = switchElement;
                if(readSizeFromCookie)var cookiePos = Get_Cookie(divs[no].id + '_attr') + '';	else cookiePos = '';
                if(divObj)cookiePos='';
                var cookieValues = new Array();


                if(cookiePos.indexOf(',')>0){
                    cookieValues = cookiePos.split(',');
                    if(!windowPositionArray[divCounter])windowPositionArray[divCounter] = new Array();
                    windowPositionArray[divCounter][0] = Math.max(0,cookieValues[0]);
                    windowPositionArray[divCounter][1] = Math.max(0,cookieValues[1]);
                }

                if(cookieValues.length==5 && !zIndexSet){
                    divs[no].style.zIndex = cookieValues[4];
                    if(cookieValues[4]/1 > currentZIndex)currentZIndex = cookieValues[4]/1;
                }
                if(windowPositionArray[divCounter]){
                    divs[no].style.left = windowPositionArray[divCounter][0] + 'px';
                    divs[no].style.top = windowPositionArray[divCounter][1] + 'px';
                }

                var subImages = divs[no].getElementsByTagName('IMG');
                for(var no2=0;no2<subImages.length;no2++){
                    if(subImages[no2].className=='resizeImage'){
                        subImages[no2].style.cursor = 'nw-resize';
                        subImages[no2].onmousedown = initResizeWindow;
                        subImages[no2].id = 'resizeImage' + divCounter;
                        break;
                    }
                    if(subImages[no2].className=='closeButton'){
                        subImages[no2].id = 'closeImage' + divCounter;
                        subImages[no2].onclick = hideWindow;
                    }
                    if(subImages[no2].className=='closeWindowLink2'){
                        subImages[no2].onclick = hideWindow;
                    }
                    if(subImages[no2].className=='minimizeButton'){
                        subImages[no2].id = 'minimizeImage' + divCounter;
                        subImages[no2].onclick = minimizeWindow;
                        if(cookieValues.length==6 && cookieValues[5]=='0'){
                            setTimeout('minimizeWindow(false,document.getElementById("minimizeImage' + divCounter + '"))',10);
                        }
                        if(cookieValues.length==6 && cookieValues[5]=='1'){
                            windowStateArray[divCounter] = 1;
                        }


                    }
                }
            }
            if(divs[no].className=='dhtmlgoodies_windowMiddle' || divs[no].className=='dhtmlgoodies_window_bottom'|| divs[no].className == 'closeWindowDiv'){
                divs[no].style.zIndex = 1000;

            }
            if(divs[no].className=='dhtmlgoodies_window_top'){
                divs[no].onmousedown = initMove;
                divs[no].id = 'top_bar'+divCounter;
                divs[no].style.zIndex = 1000;

            }

            if(divs[no].className=='dhtmlgoodies_windowContent'){
                divs[no].id = 'windowContent'+divCounter;
                divs[no].style.zIndex = 1000;
                if(cookieValues && cookieValues.length>3){
                    if(!windowSizeArray[divCounter])windowSizeArray[divCounter] = new Array();
                    windowSizeArray[divCounter][0] = cookieValues[2];
                    windowSizeArray[divCounter][1] = cookieValues[3];
                }
                if(cookieValues && cookieValues.length==5){
                    activeWindowContent = document.getElementById('windowContent' + divCounter);
                }
                if(windowSizeArray[divCounter]){
                    divs[no].style.height = windowSizeArray[divCounter][1] + 'px';
                    divs[no].parentNode.parentNode.style.width = windowSizeArray[divCounter][0] + 'px';

                    if(MSIEWIN){
                        iframe.style.width = (windowSizeArray[divCounter][0]) + 'px';
                        iframe.style.height = (windowSizeArray[divCounter][1]+20) + 'px';
                    }
                }
            }


        }

        if(!divObj){
            document.documentElement.onmouseup = stopMove;
            document.documentElement.onmousemove = moveWindow;
            document.documentElement.ondragstart = cancelEvent;
            document.documentElement.onselectstart = cancelEvent;
        }

        return divCounter;
    }

    function switchElement(e,inputElement)
	{
		if(!inputElement)inputElement = this;

        if (inputElement.id == undefined){
            return false;
        }

        var numericId = inputElement.id.replace(/[^0-9]/g,'');
		var state = '0';
		if(windowStateArray[numericId])state = '1';

		if(activeWindow && activeWindowContent){
			Set_Cookie(activeWindow.id + '_attr',activeWindow.style.left.replace('px','') + ',' + activeWindow.style.top.replace('px','') + ',' + activeWindow.style.width.replace('px','') + ',' + activeWindowContent.style.height.replace('px','') + ',' + activeWindow.style.zIndex + ',' + state,50);

		}
		currentZIndex = currentZIndex/1 + 1;
		activeWindow = document.getElementById('dhtml_goodies_id' + numericId);
		activeWindow.style.zIndex = currentZIndex;
		activeWindowContent = document.getElementById('windowContent' + numericId);

		Set_Cookie(activeWindow.id + '_attr',activeWindow.style.left.replace('px','') + ',' + activeWindow.style.top.replace('px','') + ',' + activeWindow.style.width.replace('px','') + ',' + activeWindowContent.style.height.replace('px','') + ',' + activeWindow.style.zIndex + ',' + state,50);
	}


    function createNewWindow(width,height,left,top)
	{
		var div = document.createElement('DIV');
		div.className='dhtmlgoodies_window';
		document.body.appendChild(div);




		var topDiv = document.createElement('DIV');
		topDiv.className='dhtmlgoodies_window_top';
		div.appendChild(topDiv);

		var img = document.createElement('IMG');
		img.src = '/common/images/survey_images/top_left.gif';
		img.align='left';
		topDiv.appendChild(img);

		var img = document.createElement('IMG');
		img.src = '/common/images/survey_images/top_center.gif';
		img.className='topCenterImage';
		topDiv.appendChild(img);

		var buttonDiv = document.createElement('DIV');
		buttonDiv.className='top_buttons';
		topDiv.appendChild(buttonDiv);



        var img = document.createElement('IMG');
		img.src = '/common/images/survey_images/close.gif';
		img.className='closeButton';
		buttonDiv.appendChild(img);

		var img = document.createElement('IMG');
		img.src = '/common/images/survey_images/top_right.gif';
		//buttonDiv.appendChild(img);

        var closeWindowDiv = document.createElement('DIV');
        closeWindowDiv.className = 'closeWindowDiv';
        div.appendChild(closeWindowDiv);

        var middleDiv = document.createElement('DIV');
		middleDiv.className='dhtmlgoodies_windowMiddle';
		div.appendChild(middleDiv);

        var closeWindowLink = document.createElement('IMG');
        closeWindowLink.className = 'closeWindowLink2';
        closeWindowLink.src = '/common/images/survey_images/close-window.gif';
        closeWindowLink.align = 'center';
        //closeWindowLink.textContent = 'Close this window';
        // this ID has the number 2 at the end because the close window scripts
        // use the trailing number to associate the link with the div to be
        // closed
        closeWindowLink.id = 'closeWindowLink2';
        closeWindowDiv.appendChild(closeWindowLink);

        var contentDiv = document.createElement('DIV');
		contentDiv.className='dhtmlgoodies_windowContent';
		middleDiv.appendChild(contentDiv);

		var bottomDiv = document.createElement('DIV');
		bottomDiv.className='dhtmlgoodies_window_bottom';
		div.appendChild(bottomDiv);

		var img = document.createElement('IMG');
		img.src = '/common/images/survey_images/bottom_right.gif';
		img.className='resizeImage';
		bottomDiv.appendChild(img);

		windowSizeArray[windowSizeArray.length] = [width,height];
		windowPositionArray[windowPositionArray.length] = [left,top];

		div.style.width =  width + 'px';
		contentDiv.style.height = height  + 'px';
		div.style.left =  left + 'px';
		div.style.top = top  + 'px';

		return initWindows(false,div);

	}

	function minimizeWindow(e,inputObj)
	{
		if(!inputObj)inputObj = this;
		var numericID = inputObj.id.replace(/[^0-9]/g,'');
		switchElement(false,document.getElementById('dhtml_goodies_id' + numericID));
		var state;
		if(inputObj.src.indexOf('minimize')>=0){
			activeWindowContent.style.display='none';
			document.getElementById('resizeImage'+numericID).style.display='none';
			inputObj.src = inputObj.src.replace('minimize','maximize');
			windowStateArray[numericID] = false;
			state = '0';
		}else{
			activeWindowContent.style.display='block';
			document.getElementById('resizeImage'+numericID).style.display='';
			inputObj.src = inputObj.src.replace('maximize','minimize');
			windowStateArray[numericID] = true;
			state = '1';
		}

		Set_Cookie(activeWindow.id + '_attr',activeWindow.style.left.replace('px','') + ',' + activeWindow.style.top.replace('px','') + ',' + activeWindow.style.width.replace('px','') + ',' + activeWindowContent.style.height.replace('px','') + ',' + activeWindow.style.zIndex + ',' + state,50);

	}

    initWindows();

// define the number of pages that the user should view before the survey is presented to them.
// counter that tracks page views will set itself to zero after the time period between surveys
// is reached.  That is, after the time period is up, the user will then have to view the number
// of pages specified below before the survey shows up
var maxPageViews = 5;

// define the number of days, at a minimum, between survey presentation.
var maxDaysBetweenSurvey = 90;

// the height in pixels of the survey window
var surveyWindowHeight = 400;

// the width in pixels of the survey window
var surveyWindowWidth = 650;

// the pixels from the top of the page where the survey pops open
var surveyWindowLocationTop = 150;

// the pixels from the left edge of the page where the survey pops open
var surveyWindowLocationLeft = ($(window).width() / 2) - (surveyWindowWidth / 2);

// the location of the page containing the actual survey
var surveyContentLocation = 'http://www.questionpro.com/akira/TakeSurvey?id=691078';

// ***********Note, do not change any of the values below unless you know what you are doing
// The values above are used to configure the appearance of the survey, how often is shows up etc.
// The values below are used to do the calculations to determine if the cookie should show up and
// usually shouldn't need to be changed.
var viewedCookieName = 'viewedSurvey';
var pageViewCountCookieName = 'pageCount';

// hours per day * minutes per hour * seconds per minute * millis per second
var surveyBlackoutDurationMillis = maxDaysBetweenSurvey * 24 * 60 * 60 * 1000;


function customFunctionCreateWindow()
{

    var divId = createNewWindow(surveyWindowWidth,surveyWindowHeight,surveyWindowLocationLeft,surveyWindowLocationTop);
    document.getElementById('windowContent' + divId).innerHTML = '<iframe src=\"' + surveyContentLocation + '\" name=\"adpiframe\" id=\"adpiframe\" width=\"100%\" height=\"100%\" align=\"center\" Frameborder=\"0\" Scrolling=\"yes\" marginheight=\"0\" marginwidth=\"0\"></iframe>';
    //document.getElementById('windowContent' + divId).innerHTML = 'Hey there, this is the stuff';
}

function checkViewedSurvey(){
    //debugger;
    var allCookies = document.cookie;

    // if we find the cookie with the 'viewed cookie name', that means that the user has
    // seen the survey and we don't want to show it again.  This cookie will expire by itself
    // and so all we need to know is if it still exists or not
    var position = allCookies.indexOf(viewedCookieName);

    if (position != -1){
        return true;
    }

    return false;
}

function exceedsPageViewCount(){
    var pageViews = parseInt(getPageViews());
    //debugger;
    if (pageViews > maxPageViews){
        return true;
    } else {
        return false;
    }

}

function getPageViews(){

    var numPageViews = Get_Cookie(pageViewCountCookieName);
    if (isNaN(numPageViews)){
        numPageViews = 0;
    }
    return numPageViews;

}

function shouldDisplaySurvey(){
    if (! checkViewedSurvey()){
        if (exceedsPageViewCount()){
            return true;
        }
    }

    return false;
}

function setViewedSurvey(){
    //debugger;
    var currentDate = new Date();
    var currentMillis = currentDate.getTime();
    var futureMillis = currentMillis + surveyBlackoutDurationMillis;

    var endBlackout = new Date(futureMillis);

    var cookieString = viewedCookieName + '=Y; path=/; expires=' + endBlackout.toGMTString();
    //debugger;

    document.cookie = cookieString;
}

(function($) {
    $(document).ready(function() {
       incrementPageViewCount();
       initializeSurveyIfNecessary();
     });
})(jQuery);

function incrementPageViewCount(){

    var oldValue = parseInt(getPageViews());
    var value = parseInt(oldValue) + 1;

    // now, reset this as a temporary cookie
    var cookieString = pageViewCountCookieName + '=' + value + '; path=/';
    document.cookie = cookieString;

}

function initializeSurveyIfNecessary(){
    if (shouldDisplaySurvey()){
        customFunctionCreateWindow();
        setViewedSurvey();
    }
}




